<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js coal">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Swift extensions - Andrew&#x27;s Blog</title>


        <!-- Custom HTML head -->
        
        <meta name="description" content="Andrew Ryan&#x27;s Blog">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        <link rel="stylesheet" href="../../src/style/custom.css">

        <!-- MathJax -->
        <script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    </head>
    <body>
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "coal" : "coal";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('coal')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = null;
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item affix "><a href="../../index.html">Andrew's Blog</a></li><li class="chapter-item "><a href="../../posts/linux/linux.html"><strong aria-hidden="true">1.</strong> Linux</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/linux/install_linux.html"><strong aria-hidden="true">1.1.</strong> install linux</a></li><li class="chapter-item "><a href="../../posts/linux/bash_profile.html"><strong aria-hidden="true">1.2.</strong> bash profile</a></li><li class="chapter-item "><a href="../../posts/linux/command_list.html"><strong aria-hidden="true">1.3.</strong> command list</a></li><li class="chapter-item "><a href="../../posts/linux/git_guide.html"><strong aria-hidden="true">1.4.</strong> git guide</a></li><li class="chapter-item "><a href="../../posts/linux/tar.html"><strong aria-hidden="true">1.5.</strong> tar</a></li><li class="chapter-item "><a href="../../posts/Linux/git_cheatsheet.html"><strong aria-hidden="true">1.6.</strong> Git Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/Linux/bash_cheatsheet.html"><strong aria-hidden="true">1.7.</strong> Bash Cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/macos/mac.html"><strong aria-hidden="true">2.</strong> MacOS</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/macos/macos_profiles.html"><strong aria-hidden="true">2.1.</strong> macos profiles</a></li><li class="chapter-item "><a href="../../posts/macos/macos_pwn_env_setup.html"><strong aria-hidden="true">2.2.</strong> macos pwn env setup</a></li></ol></li><li class="chapter-item expanded "><a href="../../posts/swift/swift.html"><strong aria-hidden="true">3.</strong> Swift</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/swift/learn_swift.html"><strong aria-hidden="true">3.1.</strong> learn swift basics</a></li><li class="chapter-item expanded "><a href="../../posts/swift/swift_extensions.html" class="active"><strong aria-hidden="true">3.2.</strong> Swift extensions</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_extension.html"><strong aria-hidden="true">3.3.</strong> SwiftUI extensions</a></li><li class="chapter-item "><a href="../../posts/swift/install_swift.html"><strong aria-hidden="true">3.4.</strong> install swift</a></li><li class="chapter-item "><a href="../../posts/swift/task_planner.html"><strong aria-hidden="true">3.5.</strong> implment task panner app with SwiftUI</a></li><li class="chapter-item "><a href="../../posts/swift/swift_cheat_sheet.html"><strong aria-hidden="true">3.6.</strong> Swift Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/swift/yinci_url.html"><strong aria-hidden="true">3.7.</strong> Personal privacy protocol</a></li><li class="chapter-item "><a href="../../posts/swift/swift_regular_exressions.html"><strong aria-hidden="true">3.8.</strong> Swift regular exressions</a></li><li class="chapter-item "><a href="../../posts/ios/how_to_create_beautiful_ios_charts_in_swift.html"><strong aria-hidden="true">3.9.</strong> How to Create Beautiful iOS Charts in Swift</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_source_code.html"><strong aria-hidden="true">3.10.</strong> SwiftUI source code</a></li><li class="chapter-item "><a href="../../posts/swift/use_swift_fetch_iciba_api.html"><strong aria-hidden="true">3.11.</strong> use swift fetch iciba API</a></li></ol></li><li class="chapter-item "><a href="../../posts/ios/ios.html"><strong aria-hidden="true">4.</strong> iOS</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ios/cocaposd_setup_and_install_for_ios_project.html"><strong aria-hidden="true">4.1.</strong> cocaposd setup and install for ios project</a></li><li class="chapter-item "><a href="../../posts/ios/swiftui_show_gif_image.html"><strong aria-hidden="true">4.2.</strong> SwiftUI show gif image</a></li><li class="chapter-item "><a href="../../posts/ios/implement_task_planner_app.html"><strong aria-hidden="true">4.3.</strong> implement Task planner App</a></li></ol></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c.html"><strong aria-hidden="true">5.</strong> Objective-C</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/objective_c/objective_c_cheat_sheet.html"><strong aria-hidden="true">5.1.</strong> Objective-C Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c_for_absolute_beginners_read_note.html"><strong aria-hidden="true">5.2.</strong> Objective-C Note</a></li></ol></li><li class="chapter-item "><a href="../../posts/dart/dart.html"><strong aria-hidden="true">6.</strong> Dart</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/dart/flutter.html"><strong aria-hidden="true">6.1.</strong> Flutter Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/dart/dart_cheat_sheet.html"><strong aria-hidden="true">6.2.</strong> Dart Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/flutter/flutter_dev_test.html"><strong aria-hidden="true">6.3.</strong> Flutter dev test</a></li></ol></li><li class="chapter-item "><a href="../../posts/rust/rust.html"><strong aria-hidden="true">7.</strong> Rust</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/rust/offline_use_rust.html"><strong aria-hidden="true">7.1.</strong> Offline use rust</a></li><li class="chapter-item "><a href="../../posts/rust/rust_grammer.html"><strong aria-hidden="true">7.2.</strong> rust grammar</a></li><li class="chapter-item "><a href="../../posts/rust/pase_string_and_decimal_conversion.html"><strong aria-hidden="true">7.3.</strong> pase string and decimal conversion</a></li><li class="chapter-item "><a href="../../posts/rust/parse_types.html"><strong aria-hidden="true">7.4.</strong> rust types</a></li><li class="chapter-item "><a href="../../posts/rust/rust_life_cycle.html"><strong aria-hidden="true">7.5.</strong> Rust life cycle</a></li><li class="chapter-item "><a href="../../posts/rust/rust_generic.html"><strong aria-hidden="true">7.6.</strong> rust generics</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implment_matrix.html"><strong aria-hidden="true">7.7.</strong> Rust implement matrix</a></li><li class="chapter-item "><a href="../../posts/rust/rust_sort.html"><strong aria-hidden="true">7.8.</strong> Rust implement sort algorithms</a></li><li class="chapter-item "><a href="../../posts/rust/implement_aes_encryption.html"><strong aria-hidden="true">7.9.</strong> Rust implement AEC encryption and decryption</a></li><li class="chapter-item "><a href="../../posts/rust/implement_trie_data_structure.html"><strong aria-hidden="true">7.10.</strong> implement trie data structure</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_tree.html"><strong aria-hidden="true">7.11.</strong> implement tree data_structure</a></li><li class="chapter-item "><a href="../../posts/rust/list_dir.html"><strong aria-hidden="true">7.12.</strong> list dir</a></li><li class="chapter-item "><a href="../../posts/rust/fast_way_to_implment_object_trait.html"><strong aria-hidden="true">7.13.</strong> fast way to implment object trait</a></li><li class="chapter-item "><a href="../../posts/rust/compress_rust_binary_size.html"><strong aria-hidden="true">7.14.</strong> compress rust binary size</a></li><li class="chapter-item "><a href="../../posts/rust/implment_file_upload_backend.html"><strong aria-hidden="true">7.15.</strong> impliment file upload</a></li><li class="chapter-item "><a href="../../posts/rust/this_is_add_post_cli_implementation_in_rust.html"><strong aria-hidden="true">7.16.</strong> this is add_post cli implementation in rust</a></li><li class="chapter-item "><a href="../../posts/rust/use_rust_implment_a_copyclipbord_cli.html"><strong aria-hidden="true">7.17.</strong> Use rust implment a copyclipbord CLI</a></li><li class="chapter-item "><a href="../../posts/rust/sqlite_database_add_delete_update_show_in_rust.html"><strong aria-hidden="true">7.18.</strong> sqlite database add delete update show in rust</a></li><li class="chapter-item "><a href="../../posts/rust/implementing_tokio_joinhandle_for_wasm.html"><strong aria-hidden="true">7.19.</strong> Implementing tokio JoinHandle for wasm</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_a_crate_for_encode_and_decode_brainfuck_and_ook.html"><strong aria-hidden="true">7.20.</strong> rust implement a crate for encode and decode brainfuck and ook</a></li><li class="chapter-item "><a href="../../posts/rust/slint_builtin_elements.html"><strong aria-hidden="true">7.21.</strong> Slint Builtin Elements</a></li><li class="chapter-item "><a href="../../posts/rust/corporate_network_install_rust_on_windows.html"><strong aria-hidden="true">7.22.</strong> Corporate network install Rust on windows</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_file_how_to_judge_static_link_or_dynamic_link_in_macos.html"><strong aria-hidden="true">7.23.</strong> rust binary file how to judge static link or dynamic link in Macos</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_include_dir_and_get_contents.html"><strong aria-hidden="true">7.24.</strong> rust binary include dir and get contents</a></li><li class="chapter-item "><a href="../../posts/rust/how_to_create_yolov8_based_object_detection_web_service_using_python,_julia,_node.js,_javascript,_go_and_rust.html"><strong aria-hidden="true">7.25.</strong> How to create YOLOv8-based object detection web service using Python, Julia, Node.js, JavaScript, Go and Rust</a></li><li class="chapter-item "><a href="../../posts/rust/implment_builder_proc_macro_for_command_struct.html"><strong aria-hidden="true">7.26.</strong> implment Builder proc-macro for Command struct</a></li></ol></li><li class="chapter-item "><a href="../../posts/java/java.html"><strong aria-hidden="true">8.</strong> Java</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/java/java_grammar.html"><strong aria-hidden="true">8.1.</strong> java grammar and codewar</a></li><li class="chapter-item "><a href="../../posts/java/run_jar.html"><strong aria-hidden="true">8.2.</strong> java run .jar</a></li><li class="chapter-item "><a href="../../posts/java/java_pomxml_add_defaultgoal_to_build.html"><strong aria-hidden="true">8.3.</strong> Java pomxml add defaultGoal to build</a></li><li class="chapter-item "><a href="../../posts/java/java_set_mvn_mirror.html"><strong aria-hidden="true">8.4.</strong> Java set mvn mirror</a></li></ol></li><li class="chapter-item "><a href="../../posts/python/python.html"><strong aria-hidden="true">9.</strong> Python</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/python/convert_pesn.html"><strong aria-hidden="true">9.1.</strong> convert pesn</a></li><li class="chapter-item "><a href="../../posts/python/find_remove_dir.html"><strong aria-hidden="true">9.2.</strong> find and remove dir</a></li><li class="chapter-item "><a href="../../posts/python/timing_message.html"><strong aria-hidden="true">9.3.</strong> wechat send message</a></li><li class="chapter-item "><a href="../../posts/python/use_python_openpyxl_package_read_and_edit_excel_files.html"><strong aria-hidden="true">9.4.</strong> Use python openpyxl package read and edit excel files</a></li><li class="chapter-item "><a href="../../posts/python/sanctum_model_yaml.html"><strong aria-hidden="true">9.5.</strong> sanctum model yaml</a></li><li class="chapter-item "><a href="../../posts/python/how_to_detect_objects_on_images_using_the_yolov8_neural_network.html"><strong aria-hidden="true">9.6.</strong> How to detect objects on images using the YOLOv8 neural network</a></li><li class="chapter-item "><a href="../../posts/python/use_huggingface_model.html"><strong aria-hidden="true">9.7.</strong> use huggingface model</a></li></ol></li><li class="chapter-item "><a href="../../posts/go/go.html"><strong aria-hidden="true">10.</strong> Go</a></li><li class="chapter-item "><a href="../../posts/javascript/js.html"><strong aria-hidden="true">11.</strong> Javascript</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/javascript/js_tutorial.html"><strong aria-hidden="true">11.1.</strong> js tutorial</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_map.html"><strong aria-hidden="true">11.2.</strong> ja map</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_math.html"><strong aria-hidden="true">11.3.</strong> js math</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_object.html"><strong aria-hidden="true">11.4.</strong> js object</a></li><li class="chapter-item "><a href="../../posts/javascript/js_tutorial_set.html"><strong aria-hidden="true">11.5.</strong> js set</a></li><li class="chapter-item "><a href="../../posts/javascript/single_thread_and_asynchronous.html"><strong aria-hidden="true">11.6.</strong> single thread and asynchronous</a></li><li class="chapter-item "><a href="../../posts/javascript/this.html"><strong aria-hidden="true">11.7.</strong> js this</a></li><li class="chapter-item "><a href="../../posts/javascript/js_implment_aes.html"><strong aria-hidden="true">11.8.</strong> js implment aes</a></li><li class="chapter-item "><a href="../../posts/javascript/getting_started_with_ajax.html"><strong aria-hidden="true">11.9.</strong> getting started with ajax</a></li><li class="chapter-item "><a href="../../posts/javascript/BinarySearchTree.html"><strong aria-hidden="true">11.10.</strong> binary search tree</a></li><li class="chapter-item "><a href="../../posts/javascript/goole_zx.html"><strong aria-hidden="true">11.11.</strong> goole zx</a></li><li class="chapter-item "><a href="../../posts/javascript/es6.html"><strong aria-hidden="true">11.12.</strong> es6</a></li></ol></li><li class="chapter-item "><a href="../../posts/ruby/ruby.html"><strong aria-hidden="true">12.</strong> Ruby</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ruby/rails_setup_env.html"><strong aria-hidden="true">12.1.</strong> ruby on rails setup environment</a></li><li class="chapter-item "><a href="../../posts/ruby/learn_ruby.html"><strong aria-hidden="true">12.2.</strong> learn ruby</a></li><li class="chapter-item "><a href="../../posts/ruby/ruby_note.html"><strong aria-hidden="true">12.3.</strong> Ruby Note</a></li><li class="chapter-item "><a href="../../posts/ruby/setup_ruby_for_ctf.html"><strong aria-hidden="true">12.4.</strong> Setup ruby for CTF</a></li></ol></li><li class="chapter-item "><a href="../../posts/react/react.html"><strong aria-hidden="true">13.</strong> React</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/react/react_life_cycle.html"><strong aria-hidden="true">13.1.</strong> react life cycle</a></li><li class="chapter-item "><a href="../../posts/react/react_router.html"><strong aria-hidden="true">13.2.</strong> react router</a></li><li class="chapter-item "><a href="../../posts/react/react_this.html"><strong aria-hidden="true">13.3.</strong> react this</a></li><li class="chapter-item "><a href="../../posts/react/react_interviw.html"><strong aria-hidden="true">13.4.</strong> react interview</a></li><li class="chapter-item "><a href="../../posts/react/important_react_interview.html"><strong aria-hidden="true">13.5.</strong> important react interview</a></li><li class="chapter-item "><a href="../../posts/react/react_quick_reference.html"><strong aria-hidden="true">13.6.</strong> react quick reference</a></li><li class="chapter-item "><a href="../../posts/react/redux_quick_reference.html"><strong aria-hidden="true">13.7.</strong> redux quick reference</a></li></ol></li><li class="chapter-item "><a href="../../posts/vue/vue.html"><strong aria-hidden="true">14.</strong> Vue</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/vue/vue_ajax.html"><strong aria-hidden="true">14.1.</strong> vue ajax</a></li></ol></li><li class="chapter-item "><a href="../../posts/angular/angular.html"><strong aria-hidden="true">15.</strong> Angular</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/angular/controller_communication.html"><strong aria-hidden="true">15.1.</strong> controller communication</a></li><li class="chapter-item "><a href="../../posts/angular/creating_custom_directives.html"><strong aria-hidden="true">15.2.</strong> creating custom directives</a></li><li class="chapter-item "><a href="../../posts/angular/directive_notes.html"><strong aria-hidden="true">15.3.</strong> directive notes</a></li><li class="chapter-item "><a href="../../posts/angular/directive_communication.html"><strong aria-hidden="true">15.4.</strong> directive communication</a></li><li class="chapter-item "><a href="../../posts/angular/post_params.html"><strong aria-hidden="true">15.5.</strong> post params</a></li><li class="chapter-item "><a href="../../posts/angular/read_json_angular.html"><strong aria-hidden="true">15.6.</strong> read json angular</a></li><li class="chapter-item "><a href="../../posts/angular/same_route_reload.html"><strong aria-hidden="true">15.7.</strong> same route reload</a></li></ol></li><li class="chapter-item "><a href="../../posts/css/css.html"><strong aria-hidden="true">16.</strong> Css</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/css/use_css_media.html"><strong aria-hidden="true">16.1.</strong> use css media</a></li></ol></li><li class="chapter-item "><a href="../../posts/php/php.html"><strong aria-hidden="true">17.</strong> Php</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/php/for_php_string_implment_some_extemtion_functions.html"><strong aria-hidden="true">17.1.</strong> for php string implment some extemtion functions</a></li><li class="chapter-item "><a href="../../posts/php/php_cheatsheet.html"><strong aria-hidden="true">17.2.</strong> PHP cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/windows/windows.html"><strong aria-hidden="true">18.</strong> Windows</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/windows/windows.html"><strong aria-hidden="true">18.1.</strong> Windows</a></li><li class="chapter-item "><a href="../../posts/windows/windows10_use_powershell_dedup_redundent_path.html"><strong aria-hidden="true">18.2.</strong> Windows10 use PowerShell dedup redundent PATH</a></li></ol></li><li class="chapter-item "><a href="../../posts/leetcode/leetcode.html"><strong aria-hidden="true">19.</strong> Leetcode</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/leetcode/rust_leetcode.html"><strong aria-hidden="true">19.1.</strong> rust leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_codewar.html"><strong aria-hidden="true">19.2.</strong> rust codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/swift_codewar.html"><strong aria-hidden="true">19.3.</strong> swift codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/js_leetcode.html"><strong aria-hidden="true">19.4.</strong> js leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/java_leetcode.html"><strong aria-hidden="true">19.5.</strong> java leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_huawei.html"><strong aria-hidden="true">19.6.</strong> huawei test</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_utils.html"><strong aria-hidden="true">19.7.</strong> rust common functions</a></li><li class="chapter-item "><a href="../../posts/leetcode/olympiad_training.html"><strong aria-hidden="true">19.8.</strong> Computer olympiad training</a></li></ol></li><li class="chapter-item "><a href="../../posts/ctf/CTF.html"><strong aria-hidden="true">20.</strong> CTF</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ctf/CTF_Note.html"><strong aria-hidden="true">20.1.</strong> CTF Note</a></li><li class="chapter-item "><a href="../../posts/ctf/0.1_Web.html"><strong aria-hidden="true">20.2.</strong> Web</a></li><li class="chapter-item "><a href="../../posts/ctf/4.1_Misc.html"><strong aria-hidden="true">20.3.</strong> Misc</a></li><li class="chapter-item "><a href="../../posts/ctf/3.2_PWN_note.html"><strong aria-hidden="true">20.4.</strong> PWN</a></li><li class="chapter-item "><a href="../../posts/ctf/3.1_Crypto.html"><strong aria-hidden="true">20.5.</strong> Crypto</a></li><li class="chapter-item "><a href="../../posts/ctf/3.4_RSA_note.html"><strong aria-hidden="true">20.6.</strong> Rsa attack</a></li><li class="chapter-item "><a href="../../posts/ctf/3.5_Base64.html"><strong aria-hidden="true">20.7.</strong> Base64</a></li><li class="chapter-item "><a href="../../posts/ctf/0.0_SQL Injection Cheatsheet.html"><strong aria-hidden="true">20.8.</strong> SQL Injection Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/ctf/1.1_SQL_injection.html"><strong aria-hidden="true">20.9.</strong> SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.2_SQL_injection_UNION_attacks.html"><strong aria-hidden="true">20.10.</strong> SQL Injection UNION attacks</a></li><li class="chapter-item "><a href="../../posts/ctf/1.3_Blind SQL injection.html"><strong aria-hidden="true">20.11.</strong> Blind SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.4_Code Injection.html"><strong aria-hidden="true">20.12.</strong> Code Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.5_SSRF.html"><strong aria-hidden="true">20.13.</strong> SSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.6_OS command injection.html"><strong aria-hidden="true">20.14.</strong> OS command injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.7_Local file inclusion.html"><strong aria-hidden="true">20.15.</strong> Local file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.8_Remote file inclusion.html"><strong aria-hidden="true">20.16.</strong> Remote file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.9_CSRFm.html"><strong aria-hidden="true">20.17.</strong> CSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.10_NoSQL injection.html"><strong aria-hidden="true">20.18.</strong> NoSQL injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.11_JSON injection.html"><strong aria-hidden="true">20.19.</strong> JSON injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.12_CTF_Web_SQL_Note.html"><strong aria-hidden="true">20.20.</strong> CTF Web SQL Note</a></li><li class="chapter-item "><a href="../../posts/ctf/2.1_XXE.html"><strong aria-hidden="true">20.21.</strong> XXE</a></li><li class="chapter-item "><a href="../../posts/ctf/2.2_XSS.html"><strong aria-hidden="true">20.22.</strong> XSS</a></li><li class="chapter-item "><a href="../../posts/ctf/2.3_Upload File.html"><strong aria-hidden="true">20.23.</strong> Upload File</a></li><li class="chapter-item "><a href="../../posts/ctf/2.4_serialize_unserialize.html"><strong aria-hidden="true">20.24.</strong> serialize unserialize</a></li><li class="chapter-item "><a href="../../posts/ctf/2.5_Race condition.html"><strong aria-hidden="true">20.25.</strong> Race condition</a></li><li class="chapter-item "><a href="../../posts/ctf/zip_plain_text_attack.html"><strong aria-hidden="true">20.26.</strong> Zip plain text attack</a></li><li class="chapter-item "><a href="../../posts/ctf/3.3_pwn HCTF2016 brop.html"><strong aria-hidden="true">20.27.</strong> pwn HCTF2016 brop</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_patch_defense_skill.html"><strong aria-hidden="true">20.28.</strong> PWN Patch defense skill</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_stack_overflow.html"><strong aria-hidden="true">20.29.</strong> PWN stack overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_heap_overflow.html"><strong aria-hidden="true">20.30.</strong> PWN heap overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_format_string_vulnerability.html"><strong aria-hidden="true">20.31.</strong> PWN Format String Vulnerability</a></li><li class="chapter-item "><a href="../../posts/ctf/kali_linux_tutorials.html"><strong aria-hidden="true">20.32.</strong> Kali linux tutorials</a></li><li class="chapter-item "><a href="../../posts/ctf/google_dorks_2023_lists.html"><strong aria-hidden="true">20.33.</strong> Google Dorks 2023 Lists</a></li><li class="chapter-item "><a href="../../posts/ctf/dvwa_writeup.html"><strong aria-hidden="true">20.34.</strong> DVWA WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/bwapp_writeup.html"><strong aria-hidden="true">20.35.</strong> bWAPP WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/sqlilabs_writeup.html"><strong aria-hidden="true">20.36.</strong> sqlilabs WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/pwnable_kr_challenge.html"><strong aria-hidden="true">20.37.</strong> Solutions for pwnable.kr</a></li><li class="chapter-item "><a href="../../posts/ctf/the_periodic_table.html"><strong aria-hidden="true">20.38.</strong> The Periodic Table</a></li><li class="chapter-item "><a href="../../posts/ctf/pwntools_cheatsheet.html"><strong aria-hidden="true">20.39.</strong> Pwntools Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/ctf/gdb_cheatsheet.html"><strong aria-hidden="true">20.40.</strong> GDB Cheatsheet</a></li></ol></li><li class="chapter-item "><a href="../../posts/iltes/iltes.html"><strong aria-hidden="true">21.</strong> ILTES</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/iltes/iltes_writing.html"><strong aria-hidden="true">21.1.</strong> ILTES Writing</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <!-- Track and set sidebar scroll position -->
        <script>
            var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
            sidebarScrollbox.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') {
                    sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
                }
            }, { passive: true });
            var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
            sessionStorage.removeItem('sidebar-scroll');
            if (sidebarScrollTop) {
                // preserve sidebar scroll position when navigating via links within sidebar
                sidebarScrollbox.scrollTop = sidebarScrollTop;
            } else {
                // scroll sidebar to current active section when navigating via "next/previous chapter" buttons
                var activeSection = document.querySelector('#sidebar .active');
                if (activeSection) {
                    activeSection.scrollIntoView({ block: 'center' });
                }
            }
        </script>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Andrew&#x27;s Blog</h1>

                    <div class="right-buttons">
                        <a href="https://gitee.com/dnrops/dnrops" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="swift-extensions"><a class="header" href="#swift-extensions">Swift extensions</a></h1>
<h2 id="for-string"><a class="header" href="#for-string">for String</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation
#endif

#if canImport(UIKit)
import UIKit
#endif

#if canImport(AppKit)
import AppKit
#endif

#if canImport(CoreGraphics)
import CoreGraphics
#endif

public extension String{
    func as_bytes() -&gt; Array&lt;UInt8&gt;{
        Array(self.utf8)
    }
    func len() -&gt; Int{
        self.count
    }
    func is_empty() -&gt; Bool{
        self.count == 0
    }
    func chars() -&gt; Array&lt;Element&gt;{
        Array(self)
    }
    func split(by:String) -&gt; [String]{
        self.components(separatedBy: by)
    }
    mutating func push(_ s:String){
        self.append(s)
    }
    mutating func clear(){
        self = &quot;&quot;
    }
    mutating func remove(at index:Int)-&gt;Element{
        let removeIndex = self.index(self.startIndex, offsetBy: index)
        let removed = self.remove(at: removeIndex)
        return removed
    }
    mutating func replace(from:String,to:String)-&gt;String{
        self.replacingOccurrences(of:from, with: to)
    }
    func trim()-&gt;String{
        self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
    func to_uppercase()-&gt;String{
        self.uppercased()
    }
    func to_lowercase()-&gt;String{
        self.lowercased()
    }
    func repeat_string(count:Int)-&gt;String{
        String(repeating: self, count: count)
    }
    func rfind(_ s:Character)-&gt;Optional&lt;Int&gt;{
        if let index = self.firstIndex(of: s) {
            let result = self.distance(from: self.startIndex, to: index)
            return result
        }else{
            return nil
        }
    }
    func lfind(_ s:Character)-&gt;Optional&lt;Int&gt;{
        if let index = self.lastIndex(of: s) {
            let result = self.distance(from: self.startIndex, to: index)
            return result
        }else{
            return nil
        }
    }
    func base64_encode()-&gt;String?{
        let plainData = self.data(using: .utf8)
        return plainData?.base64EncodedString()
    }
    func base64_decode()-&gt;String?{
        if let data = Data(base64Encoded: self,
                                  options: .ignoreUnknownCharacters) {
            return String(data: data, encoding: .utf8)
        }
        let remainder = count % 4
        var padding = &quot;&quot;
        if remainder &gt; 0 {
                   padding = String(repeating: &quot;=&quot;, count: 4 - remainder)
        }
        guard let data = Data(base64Encoded: self + padding,
                                     options: .ignoreUnknownCharacters) else { return nil }
        return String(data: data, encoding: .utf8)
    }
    func to_url()-&gt; URL? {
        return URL(string: self)
    }
    
    func urlDecoded()-&gt; String {
          return removingPercentEncoding ?? self
    }
    
    func urlEncoded()-&gt; String {
         return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    
    func lines() -&gt; [String] {
         var result = [String]()
         enumerateLines { line, _ in
             result.append(line)
         }
         return result
    }
    func contains(_ string: String, caseSensitive: Bool = true) -&gt; Bool {
           if !caseSensitive {
               return range(of: string, options: .caseInsensitive) != nil
           }
           return range(of: string) != nil
    }
    
    func words() -&gt; [String] {
          let characterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
          let comps = components(separatedBy: characterSet)
          return comps.filter { !$0.isEmpty }
    }
       /// SwifterSwift: Safely subscript string with index.
       ///
       ///        &quot;Hello World!&quot;[safe: 3] -&gt; &quot;l&quot;
       ///        &quot;Hello World!&quot;[safe: 20] -&gt; nil
       ///
       /// - Parameter index: index.
    subscript(safe index: Int) -&gt; Character? {
         guard index &gt;= 0, index &lt; count else { return nil }
         return self[self.index(startIndex, offsetBy: index)]
    }
      #if os(iOS) || os(macOS)
      /// SwifterSwift: Copy string to global pasteboard.
      ///
      ///        &quot;SomeText&quot;.copyToPasteboard() // copies &quot;SomeText&quot; to pasteboard
      ///
      func copyToPasteboard() {
          #if os(iOS)
          UIPasteboard.general.string = self
          #elseif os(macOS)
          NSPasteboard.general.clearContents()
          NSPasteboard.general.setString(self, forType: .string)
          #endif
      }
      #endif
    
    #if os(iOS) || os(tvOS)
   /// SwifterSwift: Check if the given string spelled correctly.
   var isSpelledCorrectly: Bool {
       let checker = UITextChecker()
       let range = NSRange(startIndex..&lt;endIndex, in: self)

       let misspelledRange = checker.rangeOfMisspelledWord(
           in: self,
           range: range,
           startingAt: 0,
           wrap: false,
           language: Locale.preferredLanguages.first ?? &quot;en&quot;)
       return misspelledRange.location == NSNotFound
   }
   #endif
}

public extension String {
    /// SwifterSwift: Array of characters of a string.
    var charactersArray: [Character] {
        return Array(self)
    }

    #if canImport(Foundation)
    /// SwifterSwift: CamelCase of string.
    ///
    ///		&quot;sOme vAriable naMe&quot;.camelCased -&gt; &quot;someVariableName&quot;
    ///
    var camelCased: String {
        let source = lowercased()
        let first = source[..&lt;source.index(after: source.startIndex)]
        if source.contains(&quot; &quot;) {
            let connected = source.capitalized.replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
            let camel = connected.replacingOccurrences(of: &quot;\n&quot;, with: &quot;&quot;)
            let rest = String(camel.dropFirst())
            return first + rest
        }
        let rest = String(source.dropFirst())
        return first + rest
    }
    #endif

    /// SwifterSwift: Check if string contains one or more emojis.
    ///
    ///		&quot;Hello 😀&quot;.containEmoji -&gt; true
    ///
    var containEmoji: Bool {
        // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F, // Emoticons
                 0x1F300...0x1F5FF, // Misc Symbols and Pictographs
                 0x1F680...0x1F6FF, // Transport and Map
                 0x1F1E6...0x1F1FF, // Regional country flags
                 0x2600...0x26FF, // Misc symbols
                 0x2700...0x27BF, // Dingbats
                 0xE0020...0xE007F, // Tags
                 0xFE00...0xFE0F, // Variation Selectors
                 0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
                 127_000...127_600, // Various asian characters
                 65024...65039, // Variation selector
                 9100...9300, // Misc items
                 8400...8447: // Combining Diacritical Marks for Symbols
                return true
            default:
                continue
            }
        }
        return false
    }

    /// SwifterSwift: First character of string (if applicable).
    ///
    ///		&quot;Hello&quot;.firstCharacterAsString -&gt; Optional(&quot;H&quot;)
    ///		&quot;&quot;.firstCharacterAsString -&gt; nil
    ///
    var firstCharacterAsString: String? {
        guard let first = first else { return nil }
        return String(first)
    }

    /// SwifterSwift: Check if string contains one or more letters.
    ///
    ///		&quot;123abc&quot;.hasLetters -&gt; true
    ///		&quot;123&quot;.hasLetters -&gt; false
    ///
    var hasLetters: Bool {
        return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
    }

    /// SwifterSwift: Check if string contains one or more numbers.
    ///
    ///		&quot;abcd&quot;.hasNumbers -&gt; false
    ///		&quot;123abc&quot;.hasNumbers -&gt; true
    ///
    var hasNumbers: Bool {
        return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
    }

    /// SwifterSwift: Check if string contains only letters.
    ///
    ///		&quot;abc&quot;.isAlphabetic -&gt; true
    ///		&quot;123abc&quot;.isAlphabetic -&gt; false
    ///
    var isAlphabetic: Bool {
        let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
        let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
        return hasLetters &amp;&amp; !hasNumbers
    }

    /// SwifterSwift: Check if string contains at least one letter and one number.
    ///
    ///		// useful for passwords
    ///		&quot;123abc&quot;.isAlphaNumeric -&gt; true
    ///		&quot;abc&quot;.isAlphaNumeric -&gt; false
    ///
    var isAlphaNumeric: Bool {
        let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
        let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
        let comps = components(separatedBy: .alphanumerics)
        return comps.joined(separator: &quot;&quot;).count == 0 &amp;&amp; hasLetters &amp;&amp; hasNumbers
    }

    /// SwifterSwift: Check if string is palindrome.
    ///
    ///     &quot;abcdcba&quot;.isPalindrome -&gt; true
    ///     &quot;Mom&quot;.isPalindrome -&gt; true
    ///     &quot;A man a plan a canal, Panama!&quot;.isPalindrome -&gt; true
    ///     &quot;Mama&quot;.isPalindrome -&gt; false
    ///
    var isPalindrome: Bool {
        let letters = filter { $0.isLetter }
        guard !letters.isEmpty else { return false }
        let midIndex = letters.index(letters.startIndex, offsetBy: letters.count / 2)
        let firstHalf = letters[letters.startIndex..&lt;midIndex]
        let secondHalf = letters[midIndex..&lt;letters.endIndex].reversed()
        return !zip(firstHalf, secondHalf).contains(where: { $0.lowercased() != $1.lowercased() })
    }

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is valid email format.
    ///
    /// - Note: Note that this property does not validate the email address against an email server. It merely attempts to determine whether its format is suitable for an email address.
    ///
    ///		&quot;john@doe.com&quot;.isValidEmail -&gt; true
    ///
    var isValidEmail: Bool {
        // http://emailregex.com/
        let regex =
            &quot;^(?:[\\p{L}0-9!#$%\\&amp;'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&amp;'*+/=?\\^_`{|}~-]+)*|\&quot;(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\&quot;)@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$&quot;
        return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid URL.
    ///
    ///		&quot;https://google.com&quot;.isValidUrl -&gt; true
    ///
    var isValidUrl: Bool {
        return URL(string: self) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid schemed URL.
    ///
    ///		&quot;https://google.com&quot;.isValidSchemedUrl -&gt; true
    ///		&quot;google.com&quot;.isValidSchemedUrl -&gt; false
    ///
    var isValidSchemedUrl: Bool {
        guard let url = URL(string: self) else { return false }
        return url.scheme != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid https URL.
    ///
    ///		&quot;https://google.com&quot;.isValidHttpsUrl -&gt; true
    ///
    var isValidHttpsUrl: Bool {
        guard let url = URL(string: self) else { return false }
        return url.scheme == &quot;https&quot;
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid http URL.
    ///
    ///		&quot;http://google.com&quot;.isValidHttpUrl -&gt; true
    ///
    var isValidHttpUrl: Bool {
        guard let url = URL(string: self) else { return false }
        return url.scheme == &quot;http&quot;
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid file URL.
    ///
    ///		&quot;file://Documents/file.txt&quot;.isValidFileUrl -&gt; true
    ///
    var isValidFileUrl: Bool {
        return URL(string: self)?.isFileURL ?? false
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string is a valid Swift number. Note: In North America, &quot;.&quot; is the decimal separator, while in many parts of Europe &quot;,&quot; is used.
    ///
    ///		&quot;123&quot;.isNumeric -&gt; true
    ///     &quot;1.3&quot;.isNumeric -&gt; true (en_US)
    ///     &quot;1,3&quot;.isNumeric -&gt; true (fr_FR)
    ///		&quot;abc&quot;.isNumeric -&gt; false
    ///
    var isNumeric: Bool {
        let scanner = Scanner(string: self)
        scanner.locale = NSLocale.current
        #if os(Linux) || targetEnvironment(macCatalyst)
        return scanner.scanDecimal() != nil &amp;&amp; scanner.isAtEnd
        #else
        return scanner.scanDecimal(nil) &amp;&amp; scanner.isAtEnd
        #endif
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if string only contains digits.
    ///
    ///     &quot;123&quot;.isDigits -&gt; true
    ///     &quot;1.3&quot;.isDigits -&gt; false
    ///     &quot;abc&quot;.isDigits -&gt; false
    ///
    var isDigits: Bool {
        return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: self))
    }
    #endif

    /// SwifterSwift: Last character of string (if applicable).
    ///
    ///		&quot;Hello&quot;.lastCharacterAsString -&gt; Optional(&quot;o&quot;)
    ///		&quot;&quot;.lastCharacterAsString -&gt; nil
    ///
    var lastCharacterAsString: String? {
        guard let last = last else { return nil }
        return String(last)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Latinized string.
    ///
    ///		&quot;Hèllö Wórld!&quot;.latinized -&gt; &quot;Hello World!&quot;
    ///
    var latinized: String {
        return folding(options: .diacriticInsensitive, locale: Locale.current)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Bool value from string (if applicable).
    ///
    ///		&quot;1&quot;.bool -&gt; true
    ///		&quot;False&quot;.bool -&gt; false
    ///		&quot;Hello&quot;.bool = nil
    ///
    var bool: Bool? {
        let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        switch selfLowercased {
        case &quot;true&quot;, &quot;yes&quot;, &quot;1&quot;:
            return true
        case &quot;false&quot;, &quot;no&quot;, &quot;0&quot;:
            return false
        default:
            return nil
        }
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Date object from &quot;yyyy-MM-dd&quot; formatted string.
    ///
    ///		&quot;2007-06-29&quot;.date -&gt; Optional(Date)
    ///
    var date: Date? {
        let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.dateFormat = &quot;yyyy-MM-dd&quot;
        return formatter.date(from: selfLowercased)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Date object from &quot;yyyy-MM-dd HH:mm:ss&quot; formatted string.
    ///
    ///		&quot;2007-06-29 14:23:09&quot;.dateTime -&gt; Optional(Date)
    ///
    var dateTime: Date? {
        let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.dateFormat = &quot;yyyy-MM-dd HH:mm:ss&quot;
        return formatter.date(from: selfLowercased)
    }
    #endif

    /// SwifterSwift: Integer value from string (if applicable).
    ///
    ///		&quot;101&quot;.int -&gt; 101
    ///
    var int: Int? {
        return Int(self)
    }

    /// SwifterSwift: Lorem ipsum string of given length.
    ///
    /// - Parameter length: number of characters to limit lorem ipsum to (default is 445 - full lorem ipsum).
    /// - Returns: Lorem ipsum dolor sit amet... string.
    static func loremIpsum(ofLength length: Int = 445) -&gt; String {
        guard length &gt; 0 else { return &quot;&quot; }

        // https://www.lipsum.com/
        let loremIpsum = &quot;&quot;&quot;
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        &quot;&quot;&quot;
        if loremIpsum.count &gt; length {
            return String(loremIpsum[loremIpsum.startIndex..&lt;loremIpsum.index(loremIpsum.startIndex, offsetBy: length)])
        }
        return loremIpsum
    }

    #if canImport(Foundation)
    /// SwifterSwift: URL from string (if applicable).
    ///
    ///		&quot;https://google.com&quot;.url -&gt; URL(string: &quot;https://google.com&quot;)
    ///		&quot;not url&quot;.url -&gt; nil
    ///
    var url: URL? {
        return URL(string: self)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: String with no spaces or new lines in beginning and end.
    ///
    ///		&quot;   hello  \n&quot;.trimmed -&gt; &quot;hello&quot;
    ///
    var trimmed: String {
        return trimmingCharacters(in: .whitespacesAndNewlines)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Readable string from a URL string.
    ///
    ///		&quot;it's%20easy%20to%20decode%20strings&quot;.urlDecoded -&gt; &quot;it's easy to decode strings&quot;
    ///
    var urlDecoded: String {
        return removingPercentEncoding ?? self
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: URL escaped string.
    ///
    ///		&quot;it's easy to encode strings&quot;.urlEncoded -&gt; &quot;it's%20easy%20to%20encode%20strings&quot;
    ///
    var urlEncoded: String {
        return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Escaped string for inclusion in a regular expression pattern.
    ///
    /// &quot;hello ^$ there&quot; -&gt; &quot;hello \\^\\$ there&quot;
    ///
    var regexEscaped: String {
        return NSRegularExpression.escapedPattern(for: self)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: String without spaces and new lines.
    ///
    ///		&quot;   \n Swifter   \n  Swift  &quot;.withoutSpacesAndNewLines -&gt; &quot;SwifterSwift&quot;
    ///
    var withoutSpacesAndNewLines: String {
        return replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;).replacingOccurrences(of: &quot;\n&quot;, with: &quot;&quot;)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Check if the given string contains only white spaces.
    var isWhitespace: Bool {
        return trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
    #endif

    #if os(iOS) || os(tvOS)
    /// SwifterSwift: Check if the given string spelled correctly.
    var isSpelledCorrectly: Bool {
        let checker = UITextChecker()
        let range = NSRange(startIndex..&lt;endIndex, in: self)

        let misspelledRange = checker.rangeOfMisspelledWord(
            in: self,
            range: range,
            startingAt: 0,
            wrap: false,
            language: Locale.preferredLanguages.first ?? &quot;en&quot;)
        return misspelledRange.location == NSNotFound
    }
    #endif
}

// MARK: - Methods

public extension String {
    #if canImport(Foundation)
    /// SwifterSwift: Float value from string (if applicable).
    ///
    /// - Parameter locale: Locale (default is Locale.current)
    /// - Returns: Optional Float value from given string.
    func float(locale: Locale = .current) -&gt; Float? {
        let formatter = NumberFormatter()
        formatter.locale = locale
        formatter.allowsFloats = true
        return formatter.number(from: self)?.floatValue
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Double value from string (if applicable).
    ///
    /// - Parameter locale: Locale (default is Locale.current)
    /// - Returns: Optional Double value from given string.
    func double(locale: Locale = .current) -&gt; Double? {
        let formatter = NumberFormatter()
        formatter.locale = locale
        formatter.allowsFloats = true
        return formatter.number(from: self)?.doubleValue
    }
    #endif

    #if canImport(CoreGraphics) &amp;&amp; canImport(Foundation)
    /// SwifterSwift: CGFloat value from string (if applicable).
    ///
    /// - Parameter locale: Locale (default is Locale.current)
    /// - Returns: Optional CGFloat value from given string.
    func cgFloat(locale: Locale = .current) -&gt; CGFloat? {
        let formatter = NumberFormatter()
        formatter.locale = locale
        formatter.allowsFloats = true
        return formatter.number(from: self) as? CGFloat
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Array of strings separated by new lines.
    ///
    ///		&quot;Hello\ntest&quot;.lines() -&gt; [&quot;Hello&quot;, &quot;test&quot;]
    ///
    /// - Returns: Strings separated by new lines.
    func lines() -&gt; [String] {
        var result = [String]()
        enumerateLines { line, _ in
            result.append(line)
        }
        return result
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Returns a localized string, with an optional comment for translators.
    ///
    ///        &quot;Hello world&quot;.localized() -&gt; Hallo Welt
    ///
    /// - Parameter comment: Optional comment for translators.
    /// - Returns: Localized string.
    func localized(comment: String = &quot;&quot;) -&gt; String {
        return NSLocalizedString(self, comment: comment)
    }
    #endif

    /// SwifterSwift: The most common character in string.
    ///
    ///		&quot;This is a test, since e is appearing everywhere e should be the common character&quot;.mostCommonCharacter() -&gt; &quot;e&quot;
    ///
    /// - Returns: The most common character.
    func mostCommonCharacter() -&gt; Character? {
        let mostCommon = withoutSpacesAndNewLines.reduce(into: [Character: Int]()) {
            let count = $0[$1] ?? 0
            $0[$1] = count + 1
        }.max { $0.1 &lt; $1.1 }?.key

        return mostCommon
    }

    /// SwifterSwift: Array with unicodes for all characters in a string.
    ///
    ///		&quot;SwifterSwift&quot;.unicodeArray() -&gt; [83, 119, 105, 102, 116, 101, 114, 83, 119, 105, 102, 116]
    ///
    /// - Returns: The unicodes for all characters in a string.
    func unicodeArray() -&gt; [Int] {
        return unicodeScalars.map { Int($0.value) }
    }

    #if canImport(Foundation)
    /// SwifterSwift: an array of all words in a string.
    ///
    ///		&quot;Swift is amazing&quot;.words() -&gt; [&quot;Swift&quot;, &quot;is&quot;, &quot;amazing&quot;]
    ///
    /// - Returns: The words contained in a string.
    func words() -&gt; [String] {
        // https://stackoverflow.com/questions/42822838
        let characterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
        let comps = components(separatedBy: characterSet)
        return comps.filter { !$0.isEmpty }
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Count of words in a string.
    ///
    ///		&quot;Swift is amazing&quot;.wordsCount() -&gt; 3
    ///
    /// - Returns: The count of words contained in a string.
    func wordCount() -&gt; Int {
        // https://stackoverflow.com/questions/42822838
        let characterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
        let comps = components(separatedBy: characterSet)
        let words = comps.filter { !$0.isEmpty }
        return words.count
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Transforms the string into a slug string.
    ///
    ///        &quot;Swift is amazing&quot;.toSlug() -&gt; &quot;swift-is-amazing&quot;
    ///
    /// - Returns: The string in slug format.
    func toSlug() -&gt; String {
        let lowercased = self.lowercased()
        let latinized = lowercased.folding(options: .diacriticInsensitive, locale: Locale.current)
        let withDashes = latinized.replacingOccurrences(of: &quot; &quot;, with: &quot;-&quot;)

        let alphanumerics = NSCharacterSet.alphanumerics
        var filtered = withDashes.filter {
            guard String($0) != &quot;-&quot; else { return true }
            guard String($0) != &quot;&amp;&quot; else { return true }
            return String($0).rangeOfCharacter(from: alphanumerics) != nil
        }

        while filtered.lastCharacterAsString == &quot;-&quot; {
            filtered = String(filtered.dropLast())
        }

        while filtered.firstCharacterAsString == &quot;-&quot; {
            filtered = String(filtered.dropFirst())
        }

        return filtered.replacingOccurrences(of: &quot;--&quot;, with: &quot;-&quot;)
    }
    #endif

    /// SwifterSwift: Safely subscript string with index.
    ///
    ///		&quot;Hello World!&quot;[safe: 3] -&gt; &quot;l&quot;
    ///		&quot;Hello World!&quot;[safe: 20] -&gt; nil
    ///
    /// - Parameter index: index.
    subscript(safe index: Int) -&gt; Character? {
        guard index &gt;= 0, index &lt; count else { return nil }
        return self[self.index(startIndex, offsetBy: index)]
    }

    /// SwifterSwift: Safely subscript string within a given range.
    ///
    ///        &quot;Hello World!&quot;[safe: 6..&lt;11] -&gt; &quot;World&quot;
    ///        &quot;Hello World!&quot;[safe: 21..&lt;110] -&gt; nil
    ///
    ///        &quot;Hello World!&quot;[safe: 6...11] -&gt; &quot;World!&quot;
    ///        &quot;Hello World!&quot;[safe: 21...110] -&gt; nil
    ///
    /// - Parameter range: Range expression.
    subscript&lt;R&gt;(safe range: R) -&gt; String? where R: RangeExpression, R.Bound == Int {
        let range = range.relative(to: Int.min..&lt;Int.max)
        guard range.lowerBound &gt;= 0,
            let lowerIndex = index(startIndex, offsetBy: range.lowerBound, limitedBy: endIndex),
            let upperIndex = index(startIndex, offsetBy: range.upperBound, limitedBy: endIndex) else {
            return nil
        }

        return String(self[lowerIndex..&lt;upperIndex])
    }

    #if os(iOS) || os(macOS)
    /// SwifterSwift: Copy string to global pasteboard.
    ///
    ///		&quot;SomeText&quot;.copyToPasteboard() // copies &quot;SomeText&quot; to pasteboard
    ///
    func copyToPasteboard() {
        #if os(iOS)
        UIPasteboard.general.string = self
        #elseif os(macOS)
        NSPasteboard.general.clearContents()
        NSPasteboard.general.setString(self, forType: .string)
        #endif
    }
    #endif

    /// SwifterSwift: Converts string format to CamelCase.
    ///
    ///		var str = &quot;sOme vaRiabLe Name&quot;
    ///		str.camelize()
    ///		print(str) // prints &quot;someVariableName&quot;
    ///
    @discardableResult
    mutating func camelize() -&gt; String {
        let source = lowercased()
        let first = source[..&lt;source.index(after: source.startIndex)]
        if source.contains(&quot; &quot;) {
            let connected = source.capitalized.replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
            let camel = connected.replacingOccurrences(of: &quot;\n&quot;, with: &quot;&quot;)
            let rest = String(camel.dropFirst())
            self = first + rest
            return self
        }
        let rest = String(source.dropFirst())

        self = first + rest
        return self
    }

    /// SwifterSwift: First character of string uppercased(if applicable) while keeping the original string.
    ///
    ///        &quot;hello world&quot;.firstCharacterUppercased() -&gt; &quot;Hello world&quot;
    ///        &quot;&quot;.firstCharacterUppercased() -&gt; &quot;&quot;
    ///
    mutating func firstCharacterUppercased() {
        guard let first = first else { return }
        self = String(first).uppercased() + dropFirst()
    }

    /// SwifterSwift: Check if string contains only unique characters.
    ///
    func hasUniqueCharacters() -&gt; Bool {
        guard count &gt; 0 else { return false }
        var uniqueChars = Set&lt;String&gt;()
        for char in self {
            if uniqueChars.contains(String(char)) { return false }
            uniqueChars.insert(String(char))
        }
        return true
    }

    #if canImport(Foundation)
    /// SwifterSwift: Check if string contains one or more instance of substring.
    ///
    ///		&quot;Hello World!&quot;.contain(&quot;O&quot;) -&gt; false
    ///		&quot;Hello World!&quot;.contain(&quot;o&quot;, caseSensitive: false) -&gt; true
    ///
    /// - Parameters:
    ///   - string: substring to search for.
    ///   - caseSensitive: set true for case sensitive search (default is true).
    /// - Returns: true if string contains one or more instance of substring.
    func contains(_ string: String, caseSensitive: Bool = true) -&gt; Bool {
        if !caseSensitive {
            return range(of: string, options: .caseInsensitive) != nil
        }
        return range(of: string) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Count of substring in string.
    ///
    ///		&quot;Hello World!&quot;.count(of: &quot;o&quot;) -&gt; 2
    ///		&quot;Hello World!&quot;.count(of: &quot;L&quot;, caseSensitive: false) -&gt; 3
    ///
    /// - Parameters:
    ///   - string: substring to search for.
    ///   - caseSensitive: set true for case sensitive search (default is true).
    /// - Returns: count of appearance of substring in string.
    func count(of string: String, caseSensitive: Bool = true) -&gt; Int {
        if !caseSensitive {
            return lowercased().components(separatedBy: string.lowercased()).count - 1
        }
        return components(separatedBy: string).count - 1
    }
    #endif

    /// SwifterSwift: Check if string ends with substring.
    ///
    ///		&quot;Hello World!&quot;.ends(with: &quot;!&quot;) -&gt; true
    ///		&quot;Hello World!&quot;.ends(with: &quot;WoRld!&quot;, caseSensitive: false) -&gt; true
    ///
    /// - Parameters:
    ///   - suffix: substring to search if string ends with.
    ///   - caseSensitive: set true for case sensitive search (default is true).
    /// - Returns: true if string ends with substring.
    func ends(with suffix: String, caseSensitive: Bool = true) -&gt; Bool {
        if !caseSensitive {
            return lowercased().hasSuffix(suffix.lowercased())
        }
        return hasSuffix(suffix)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Latinize string.
    ///
    ///		var str = &quot;Hèllö Wórld!&quot;
    ///		str.latinize()
    ///		print(str) // prints &quot;Hello World!&quot;
    ///
    @discardableResult
    mutating func latinize() -&gt; String {
        self = folding(options: .diacriticInsensitive, locale: Locale.current)
        return self
    }
    #endif

    /// SwifterSwift: Random string of given length.
    ///
    ///		String.random(ofLength: 18) -&gt; &quot;u7MMZYvGo9obcOcPj8&quot;
    ///
    /// - Parameter length: number of characters in string.
    /// - Returns: random string of given length.
    static func random(ofLength length: Int) -&gt; String {
        guard length &gt; 0 else { return &quot;&quot; }
        let base = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;
        var randomString = &quot;&quot;
        for _ in 1...length {
            randomString.append(base.randomElement()!)
        }
        return randomString
    }

    /// SwifterSwift: Reverse string.
    @discardableResult
    mutating func reverse() -&gt; String {
        let chars: [Character] = reversed()
        self = String(chars)
        return self
    }

    /// SwifterSwift: Sliced string from a start index with length.
    ///
    ///        &quot;Hello World&quot;.slicing(from: 6, length: 5) -&gt; &quot;World&quot;
    ///
    /// - Parameters:
    ///   - index: string index the slicing should start from.
    ///   - length: amount of characters to be sliced after given index.
    /// - Returns: sliced substring of length number of characters (if applicable) (example: &quot;Hello World&quot;.slicing(from: 6, length: 5) -&gt; &quot;World&quot;).
    func slicing(from index: Int, length: Int) -&gt; String? {
        guard length &gt;= 0, index &gt;= 0, index &lt; count else { return nil }
        guard index.advanced(by: length) &lt;= count else {
            return self[safe: index..&lt;count]
        }
        guard length &gt; 0 else { return &quot;&quot; }
        return self[safe: index..&lt;index.advanced(by: length)]
    }

    /// SwifterSwift: Slice given string from a start index with length (if applicable).
    ///
    ///		var str = &quot;Hello World&quot;
    ///		str.slice(from: 6, length: 5)
    ///		print(str) // prints &quot;World&quot;
    ///
    /// - Parameters:
    ///   - index: string index the slicing should start from.
    ///   - length: amount of characters to be sliced after given index.
    @discardableResult
    mutating func slice(from index: Int, length: Int) -&gt; String {
        if let str = slicing(from: index, length: length) {
            self = String(str)
        }
        return self
    }

    /// SwifterSwift: Slice given string from a start index to an end index (if applicable).
    ///
    ///		var str = &quot;Hello World&quot;
    ///		str.slice(from: 6, to: 11)
    ///		print(str) // prints &quot;World&quot;
    ///
    /// - Parameters:
    ///   - start: string index the slicing should start from.
    ///   - end: string index the slicing should end at.
    @discardableResult
    mutating func slice(from start: Int, to end: Int) -&gt; String {
        guard end &gt;= start else { return self }
        if let str = self[safe: start..&lt;end] {
            self = str
        }
        return self
    }

    /// SwifterSwift: Slice given string from a start index (if applicable).
    ///
    ///		var str = &quot;Hello World&quot;
    ///		str.slice(at: 6)
    ///		print(str) // prints &quot;World&quot;
    ///
    /// - Parameter index: string index the slicing should start from.
    @discardableResult
    mutating func slice(at index: Int) -&gt; String {
        guard index &lt; count else { return self }
        if let str = self[safe: index..&lt;count] {
            self = str
        }
        return self
    }

    /// SwifterSwift: Check if string starts with substring.
    ///
    ///		&quot;hello World&quot;.starts(with: &quot;h&quot;) -&gt; true
    ///		&quot;hello World&quot;.starts(with: &quot;H&quot;, caseSensitive: false) -&gt; true
    ///
    /// - Parameters:
    ///   - suffix: substring to search if string starts with.
    ///   - caseSensitive: set true for case sensitive search (default is true).
    /// - Returns: true if string starts with substring.
    func starts(with prefix: String, caseSensitive: Bool = true) -&gt; Bool {
        if !caseSensitive {
            return lowercased().hasPrefix(prefix.lowercased())
        }
        return hasPrefix(prefix)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Date object from string of date format.
    ///
    ///		&quot;2017-01-15&quot;.date(withFormat: &quot;yyyy-MM-dd&quot;) -&gt; Date set to Jan 15, 2017
    ///		&quot;not date string&quot;.date(withFormat: &quot;yyyy-MM-dd&quot;) -&gt; nil
    ///
    /// - Parameter format: date format.
    /// - Returns: Date object from string (if applicable).
    func date(withFormat format: String) -&gt; Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: self)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Removes spaces and new lines in beginning and end of string.
    ///
    ///		var str = &quot;  \n Hello World \n\n\n&quot;
    ///		str.trim()
    ///		print(str) // prints &quot;Hello World&quot;
    ///
    @discardableResult
    mutating func trim() -&gt; String {
        self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        return self
    }
    #endif

    /// SwifterSwift: Truncate string (cut it to a given number of characters).
    ///
    ///		var str = &quot;This is a very long sentence&quot;
    ///		str.truncate(toLength: 14)
    ///		print(str) // prints &quot;This is a very...&quot;
    ///
    /// - Parameters:
    ///   - toLength: maximum number of characters before cutting.
    ///   - trailing: string to add at the end of truncated string (default is &quot;...&quot;).
    @discardableResult
    mutating func truncate(toLength length: Int, trailing: String? = &quot;...&quot;) -&gt; String {
        guard length &gt; 0 else { return self }
        if count &gt; length {
            self = self[startIndex..&lt;index(startIndex, offsetBy: length)] + (trailing ?? &quot;&quot;)
        }
        return self
    }

    /// SwifterSwift: Truncated string (limited to a given number of characters).
    ///
    ///		&quot;This is a very long sentence&quot;.truncated(toLength: 14) -&gt; &quot;This is a very...&quot;
    ///		&quot;Short sentence&quot;.truncated(toLength: 14) -&gt; &quot;Short sentence&quot;
    ///
    /// - Parameters:
    ///   - toLength: maximum number of characters before cutting.
    ///   - trailing: string to add at the end of truncated string.
    /// - Returns: truncated string (this is an extr...).
    func truncated(toLength length: Int, trailing: String? = &quot;...&quot;) -&gt; String {
        guard 0..&lt;count ~= length else { return self }
        return self[startIndex..&lt;index(startIndex, offsetBy: length)] + (trailing ?? &quot;&quot;)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Convert URL string to readable string.
    ///
    ///		var str = &quot;it's%20easy%20to%20decode%20strings&quot;
    ///		str.urlDecode()
    ///		print(str) // prints &quot;it's easy to decode strings&quot;
    ///
    @discardableResult
    mutating func urlDecode() -&gt; String {
        if let decoded = removingPercentEncoding {
            self = decoded
        }
        return self
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Escape string.
    ///
    ///		var str = &quot;it's easy to encode strings&quot;
    ///		str.urlEncode()
    ///		print(str) // prints &quot;it's%20easy%20to%20encode%20strings&quot;
    ///
    @discardableResult
    mutating func urlEncode() -&gt; String {
        if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            self = encoded
        }
        return self
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Verify if string matches the regex pattern.
    ///
    /// - Parameter pattern: Pattern to verify.
    /// - Returns: `true` if string matches the pattern.
    func matches(pattern: String) -&gt; Bool {
        return range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Verify if string matches the regex.
    ///
    /// - Parameters:
    ///   - regex: Regex to verify.
    ///   - options: The matching options to use.
    /// - Returns: `true` if string matches the regex.
    func matches(regex: NSRegularExpression, options: NSRegularExpression.MatchingOptions = []) -&gt; Bool {
        let range = NSRange(startIndex..&lt;endIndex, in: self)
        return regex.firstMatch(in: self, options: options, range: range) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Overload Swift's 'contains' operator for matching regex pattern.
    ///
    /// - Parameters:
    ///   - lhs: String to check on regex pattern.
    ///   - rhs: Regex pattern to match against.
    /// - Returns: true if string matches the pattern.
    static func ~= (lhs: String, rhs: String) -&gt; Bool {
        return lhs.range(of: rhs, options: .regularExpression) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Overload Swift's 'contains' operator for matching regex.
    ///
    /// - Parameters:
    ///   - lhs: String to check on regex.
    ///   - rhs: Regex to match against.
    /// - Returns: `true` if there is at least one match for the regex in the string.
    static func ~= (lhs: String, rhs: NSRegularExpression) -&gt; Bool {
        let range = NSRange(lhs.startIndex..&lt;lhs.endIndex, in: lhs)
        return rhs.firstMatch(in: lhs, range: range) != nil
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Returns a new string in which all occurrences of a regex in a specified range of the receiver are replaced by the template.
    /// - Parameters:
    ///   - regex Regex to replace.
    ///   - template: The template to replace the regex.
    ///   - options: The matching options to use
    ///   - searchRange: The range in the receiver in which to search.
    /// - Returns: A new string in which all occurrences of regex in searchRange of the receiver are replaced by template.
    func replacingOccurrences(
        of regex: NSRegularExpression,
        with template: String,
        options: NSRegularExpression.MatchingOptions = [],
        range searchRange: Range&lt;String.Index&gt;? = nil) -&gt; String {
        let range = NSRange(searchRange ?? startIndex..&lt;endIndex, in: self)
        return regex.stringByReplacingMatches(in: self, options: options, range: range, withTemplate: template)
    }
    #endif

    /// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
    ///
    ///   &quot;hue&quot;.padStart(10) -&gt; &quot;       hue&quot;
    ///   &quot;hue&quot;.padStart(10, with: &quot;br&quot;) -&gt; &quot;brbrbrbhue&quot;
    ///
    /// - Parameters:
    ///   - length: The target length to pad.
    ///   - string: Pad string. Default is &quot; &quot;.
    @discardableResult
    mutating func padStart(_ length: Int, with string: String = &quot; &quot;) -&gt; String {
        self = paddingStart(length, with: string)
        return self
    }

    /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the start.
    ///
    ///   &quot;hue&quot;.paddingStart(10) -&gt; &quot;       hue&quot;
    ///   &quot;hue&quot;.paddingStart(10, with: &quot;br&quot;) -&gt; &quot;brbrbrbhue&quot;
    ///
    /// - Parameters:
    ///   - length: The target length to pad.
    ///   - string: Pad string. Default is &quot; &quot;.
    /// - Returns: The string with the padding on the start.
    func paddingStart(_ length: Int, with string: String = &quot; &quot;) -&gt; String {
        guard count &lt; length else { return self }

        let padLength = length - count
        if padLength &lt; string.count {
            return string[string.startIndex..&lt;string.index(string.startIndex, offsetBy: padLength)] + self
        } else {
            var padding = string
            while padding.count &lt; padLength {
                padding.append(string)
            }
            return padding[padding.startIndex..&lt;padding.index(padding.startIndex, offsetBy: padLength)] + self
        }
    }

    /// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
    ///
    ///   &quot;hue&quot;.padEnd(10) -&gt; &quot;hue       &quot;
    ///   &quot;hue&quot;.padEnd(10, with: &quot;br&quot;) -&gt; &quot;huebrbrbrb&quot;
    ///
    /// - Parameters:
    ///   - length: The target length to pad.
    ///   - string: Pad string. Default is &quot; &quot;.
    @discardableResult
    mutating func padEnd(_ length: Int, with string: String = &quot; &quot;) -&gt; String {
        self = paddingEnd(length, with: string)
        return self
    }

    /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the end.
    ///
    ///   &quot;hue&quot;.paddingEnd(10) -&gt; &quot;hue       &quot;
    ///   &quot;hue&quot;.paddingEnd(10, with: &quot;br&quot;) -&gt; &quot;huebrbrbrb&quot;
    ///
    /// - Parameters:
    ///   - length: The target length to pad.
    ///   - string: Pad string. Default is &quot; &quot;.
    /// - Returns: The string with the padding on the end.
    func paddingEnd(_ length: Int, with string: String = &quot; &quot;) -&gt; String {
        guard count &lt; length else { return self }

        let padLength = length - count
        if padLength &lt; string.count {
            return self + string[string.startIndex..&lt;string.index(string.startIndex, offsetBy: padLength)]
        } else {
            var padding = string
            while padding.count &lt; padLength {
                padding.append(string)
            }
            return self + padding[padding.startIndex..&lt;padding.index(padding.startIndex, offsetBy: padLength)]
        }
    }

    /// SwifterSwift: Removes given prefix from the string.
    ///
    ///   &quot;Hello, World!&quot;.removingPrefix(&quot;Hello, &quot;) -&gt; &quot;World!&quot;
    ///
    /// - Parameter prefix: Prefix to remove from the string.
    /// - Returns: The string after prefix removing.
    func removingPrefix(_ prefix: String) -&gt; String {
        guard hasPrefix(prefix) else { return self }
        return String(dropFirst(prefix.count))
    }

    /// SwifterSwift: Removes given suffix from the string.
    ///
    ///   &quot;Hello, World!&quot;.removingSuffix(&quot;, World!&quot;) -&gt; &quot;Hello&quot;
    ///
    /// - Parameter suffix: Suffix to remove from the string.
    /// - Returns: The string after suffix removing.
    func removingSuffix(_ suffix: String) -&gt; String {
        guard hasSuffix(suffix) else { return self }
        return String(dropLast(suffix.count))
    }

    /// SwifterSwift: Adds prefix to the string.
    ///
    ///     &quot;www.apple.com&quot;.withPrefix(&quot;https://&quot;) -&gt; &quot;https://www.apple.com&quot;
    ///
    /// - Parameter prefix: Prefix to add to the string.
    /// - Returns: The string with the prefix prepended.
    func withPrefix(_ prefix: String) -&gt; String {
        // https://www.hackingwithswift.com/articles/141/8-useful-swift-extensions
        guard !hasPrefix(prefix) else { return self }
        return prefix + self
    }
}

// MARK: - Initializers

public extension String {
    #if canImport(Foundation)
    /// SwifterSwift: Create a new string from a base64 string (if applicable).
    ///
    ///		String(base64: &quot;SGVsbG8gV29ybGQh&quot;) = &quot;Hello World!&quot;
    ///		String(base64: &quot;hello&quot;) = nil
    ///
    /// - Parameter base64: base64 string.
    init?(base64: String) {
        guard let decodedData = Data(base64Encoded: base64) else { return nil }
        guard let str = String(data: decodedData, encoding: .utf8) else { return nil }
        self.init(str)
    }
    #endif

    /// SwifterSwift: Create a new random string of given length.
    ///
    ///		String(randomOfLength: 10) -&gt; &quot;gY8r3MHvlQ&quot;
    ///
    /// - Parameter length: number of characters in string.
    init(randomOfLength length: Int) {
        guard length &gt; 0 else {
            self.init()
            return
        }

        let base = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;
        var randomString = &quot;&quot;
        for _ in 1...length {
            randomString.append(base.randomElement()!)
        }
        self = randomString
    }
}

#if !os(Linux)

// MARK: - NSAttributedString

public extension String {
    #if os(iOS) || os(macOS)
    /// SwifterSwift: Bold string.
    var bold: NSAttributedString {
        return NSMutableAttributedString(
            string: self,
            attributes: [.font: SFFont.boldSystemFont(ofSize: SFFont.systemFontSize)])
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Underlined string
    var underline: NSAttributedString {
        return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Strikethrough string.
    var strikethrough: NSAttributedString {
        return NSAttributedString(
            string: self,
            attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
    }
    #endif

    #if os(iOS)
    /// SwifterSwift: Italic string.
    var italic: NSAttributedString {
        return NSMutableAttributedString(
            string: self,
            attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
    }
    #endif

    #if canImport(AppKit) || canImport(UIKit)
    /// SwifterSwift: Add color to string.
    ///
    /// - Parameter color: text color.
    /// - Returns: a NSAttributedString versions of string colored with given color.
    func colored(with color: SFColor) -&gt; NSAttributedString {
        return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color])
    }
    #endif
}

#endif

// MARK: - Operators

public extension String {
    /// SwifterSwift: Repeat string multiple times.
    ///
    ///        'bar' * 3 -&gt; &quot;barbarbar&quot;
    ///
    /// - Parameters:
    ///   - lhs: string to repeat.
    ///   - rhs: number of times to repeat character.
    /// - Returns: new string with given string repeated n times.
    static func * (lhs: String, rhs: Int) -&gt; String {
        guard rhs &gt; 0 else { return &quot;&quot; }
        return String(repeating: lhs, count: rhs)
    }

    /// SwifterSwift: Repeat string multiple times.
    ///
    ///        3 * 'bar' -&gt; &quot;barbarbar&quot;
    ///
    /// - Parameters:
    ///   - lhs: number of times to repeat character.
    ///   - rhs: string to repeat.
    /// - Returns: new string with given string repeated n times.
    static func * (lhs: Int, rhs: String) -&gt; String {
        guard lhs &gt; 0 else { return &quot;&quot; }
        return String(repeating: rhs, count: lhs)
    }
}

#if canImport(Foundation)

// MARK: - NSString extensions

public extension String {
    /// SwifterSwift: NSString from a string.
    var nsString: NSString {
        return NSString(string: self)
    }

    /// SwifterSwift: The full `NSRange` of the string.
    var fullNSRange: NSRange { NSRange(startIndex..&lt;endIndex, in: self) }

    /// SwifterSwift: NSString lastPathComponent.
    var lastPathComponent: String {
        return (self as NSString).lastPathComponent
    }

    /// SwifterSwift: NSString pathExtension.
    var pathExtension: String {
        return (self as NSString).pathExtension
    }

    /// SwifterSwift: NSString deletingLastPathComponent.
    var deletingLastPathComponent: String {
        return (self as NSString).deletingLastPathComponent
    }

    /// SwifterSwift: NSString deletingPathExtension.
    var deletingPathExtension: String {
        return (self as NSString).deletingPathExtension
    }

    /// SwifterSwift: NSString pathComponents.
    var pathComponents: [String] {
        return (self as NSString).pathComponents
    }

    /// SwifterSwift: Convert an `NSRange` into `Range&lt;String.Index&gt;`.
    /// - Parameter nsRange: The `NSRange` within the receiver.
    /// - Returns: The equivalent `Range&lt;String.Index&gt;` of `nsRange` found within the receiving string.
    func range(from nsRange: NSRange) -&gt; Range&lt;Index&gt; {
        guard let range = Range(nsRange, in: self) else { fatalError(&quot;Failed to find range \(nsRange) in \(self)&quot;) }
        return range
    }

    /// SwifterSwift: Convert a `Range&lt;String.Index&gt;` into `NSRange`.
    /// - Parameter range: The `Range&lt;String.Index&gt;` within the receiver.
    /// - Returns: The equivalent `NSRange` of `range` found within the receiving string.
    func nsRange(from range: Range&lt;Index&gt;) -&gt; NSRange {
        return NSRange(range, in: self)
    }

    /// SwifterSwift: NSString appendingPathComponent(str: String).
    ///
    /// - Note: This method only works with file paths (not, for example, string representations of URLs.
    ///   See NSString [appendingPathComponent(_:)](https://developer.apple.com/documentation/foundation/nsstring/1417069-appendingpathcomponent)
    /// - Parameter str: the path component to append to the receiver.
    /// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
    func appendingPathComponent(_ str: String) -&gt; String {
        return (self as NSString).appendingPathComponent(str)
    }

    /// SwifterSwift: NSString appendingPathExtension(str: String).
    ///
    /// - Parameter str: The extension to append to the receiver.
    /// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
    func appendingPathExtension(_ str: String) -&gt; String? {
        return (self as NSString).appendingPathExtension(str)
    }

    /// SwifterSwift: Accesses a contiguous subrange of the collection’s elements.
    /// - Parameter nsRange: A range of the collection’s indices. The bounds of the range must be valid indices of the collection.
    /// - Returns: A slice of the receiving string.
    subscript(bounds: NSRange) -&gt; Substring {
        guard let range = Range(bounds, in: self) else { fatalError(&quot;Failed to find range \(bounds) in \(self)&quot;) }
        return self[range]
    }
}

#endif



// MARK: - String extension

/// This extesion adds some useful functions to String.
public extension String {
    // MARK: - Variables

    /// Gets the individual characters and puts them in an array as Strings.
    var array: [String] {
        description.map { String($0) }
    }
    
    /// Returns the Float value
    var floatValue: Float {
        NSString(string: self).floatValue
    }
    
    /// Returns the Int value
    var intValue: Int {
        Int(NSString(string: self).intValue)
    }

    /// Convert self to a Data.
    var dataValue: Data? {
        data(using: .utf8)
    }
    
    /// Encoded string to Base64.
    var base64encoded: String {
        guard let data: Data = data(using: .utf8) else {
            return &quot;&quot;
        }
        
        return data.base64EncodedString()
    }
    
    /// Decoded Base64 to string.
    var base64decoded: String {
        guard let data = Data(base64Encoded: String(self), options: .ignoreUnknownCharacters), let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else {
            return &quot;&quot;
        }
        
        return String(describing: dataString)
    }
    
    /// Encode self to an encoded url string.
    var urlEncoded: String? {
        addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
    }
    
    /// Returns the localized string from self.
    var localized: String {
        NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: &quot;&quot;, comment: &quot;&quot;)
    }
    
    /// Convert the String to a NSNumber.
    var numberValue: NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
    
    // MARK: - Functions
    
    /// Get the character at a given index.
    ///
    /// - Parameter index: The index.
    /// - Returns: Returns the character at a given index, starts from 0.
    func character(at index: Int) -&gt; Character {
        self[self.index(startIndex, offsetBy: index)]
    }
    
    /// Returns a new string containing the characters of the String from the one at a given index to the end.
    ///
    /// - Parameter index: The index.
    /// - Returns: Returns the substring from index.
    func substring(from index: Int) -&gt; String {
        String(self[self.index(startIndex, offsetBy: index)...])
    }
    
    /// Creates a substring from the given character.
    ///
    /// - Parameter character: The character.
    /// - Returns: Returns the substring from character.
    func substring(from character: Character) -&gt; String {
        let index = self.index(of: character)
        guard index &gt; -1 else {
            return &quot;&quot;
        }
        
        return substring(from: index + 1)
    }
    
    /// Returns a new string containing the characters of the String up to, but not including, the one at a given index.
    ///
    /// - Parameter index: The index.
    /// - Returns: Returns the substring to index.
    func substring(to index: Int) -&gt; String {
        guard index &lt;= count else {
            return &quot;&quot;
        }
        
        return String(self[..&lt;self.index(startIndex, offsetBy: index)])
    }
    
    /// Creates a substring to the given character.
    ///
    /// - Parameter character: The character.
    /// - Returns: Returns the substring to character.
    func substring(to character: Character) -&gt; String {
        let index: Int = self.index(of: character)
        guard index &gt; -1 else {
            return &quot;&quot;
        }
        
        return substring(to: index)
    }
    
    /// Creates a substring with a given range.
    ///
    /// - Parameter range: The range.
    /// - Returns: Returns the string between the range.
    func substring(with range: Range&lt;Int&gt;) -&gt; String {
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(startIndex, offsetBy: range.upperBound)

        return String(self[start..&lt;end])
    }
    
    /// Creates a substring with a given range.
    ///
    /// - Parameter range: The range.
    /// - Returns: Returns the string between the range.
    func substring(with range: CountableClosedRange&lt;Int&gt;) -&gt; String {
        substring(with: Range(uncheckedBounds: (lower: range.lowerBound, upper: range.upperBound + 1)))
    }
    
    /// Returns the index of the given character.
    ///
    /// - Parameter character: The character to search.
    /// - Returns: Returns the index of the given character, -1 if not found.
    func index(of character: Character) -&gt; Int {
        guard let index: Index = firstIndex(of: character) else {
            return -1
        }
        
        return distance(from: startIndex, to: index)
    }
    
    /// Check if self has the given substring in case-sensitiv or case-insensitive.
    ///
    /// - Parameters:
    ///   - string: The substring to be searched.
    ///   - caseSensitive: If the search has to be case-sensitive or not.
    /// - Returns: Returns true if founded, otherwise false.
    func range(of string: String, caseSensitive: Bool = true) -&gt; Bool {
        caseSensitive ? (range(of: string) != nil) : (lowercased().range(of: string.lowercased()) != nil)
    }
    
    /// Check if self has the given substring in case-sensitiv or case-insensitive.
    ///
    /// - Parameters:
    ///   - string: The substring to be searched.
    ///   - caseSensitive: If the search has to be case-sensitive or not.
    /// - Returns: Returns true if founded, otherwise false.
    func has(_ string: String, caseSensitive: Bool = true) -&gt; Bool {
        range(of: string, caseSensitive: caseSensitive)
    }
    
    /// Returns the number of occurrences of a String into 
    ///
    /// - Parameter string: String of occurrences.
    /// - Returns: Returns the number of occurrences of a String into 
    func occurrences(of string: String, caseSensitive: Bool = true) -&gt; Int {
        var string = string
        if !caseSensitive {
            string = string.lowercased()
        }
        return lowercased().components(separatedBy: string).count - 1
    }
    
    /// Conver self to a capitalized string.
    /// Example: &quot;This is a Test&quot; will return &quot;This is a test&quot; and &quot;this is a test&quot; will return &quot;This is a test&quot;.
    ///
    /// - Returns: Returns the capitalized sentence string.
    func sentenceCapitalizedString() -&gt; String {
        guard !isEmpty else {
            return &quot;&quot;
        }
        
        let uppercase: String = substring(to: 1).uppercased()
        let lowercase: String = substring(from: 1).lowercased()

        return uppercase + lowercase
    }
    
    /// Returns the query parameter string.
    ///
    /// - Parameter parameter: Parameter to be searched.
    /// - Returns: Returns the query parameter string.
    func queryStringParameter(parameter: String) -&gt; String? {
        guard let url = URLComponents(string: self) else {
            return nil
        }
        
        return url.queryItems?.first { $0.name == parameter }?.value
    }
    
    /// Converts the query to a dictionary of parameters.
    ///
    /// - Returns: Returns the dictionary of parameters.
    func queryDictionary() -&gt; [String: String] {
        var queryStrings: [String: String] = [:]
        for pair in self.components(separatedBy: &quot;&amp;&quot;) {
            let key = pair.components(separatedBy: &quot;=&quot;)[0]
            let value = pair.components(separatedBy: &quot;=&quot;)[1].replacingOccurrences(of: &quot;+&quot;, with: &quot; &quot;).removingPercentEncoding ?? &quot;&quot;
            
            queryStrings[key] = value
        }
        return queryStrings
    }
    
    #if !os(Linux)
        /// Check if the URL is a valid HTTP URL.
        ///
        /// - Returns: Returns if the URL is a valid HTTP URL
        func isURLValid() -&gt; Bool {
            let regEx = &quot;((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))?.+&quot;
            let predicate = NSPredicate(format: &quot;SELF MATCHES %@&quot;, argumentArray: [regEx])
            return predicate.evaluate(with: self)
        }
    #endif
    
    /// Convert a String to a NSAttributedString.
    /// With that variable you can customize a String with a style.
    ///
    /// Example:
    ///
    ///     string.attributedString.font(UIFont(fontName: .helveticaNeue, size: 20))
    ///
    /// You can even concatenate two or more styles:
    ///
    ///     string.attributedString.font(UIFont(fontName: .helveticaNeue, size: 20)).backgroundColor(UIColor.red)
    var attributedString: NSAttributedString {
        NSAttributedString(string: self)
    }
    
    /// Returns the last path component.
    var lastPathComponent: String {
        NSString(string: self).lastPathComponent
    }

    /// Returns the path extension.
    var pathExtension: String {
        NSString(string: self).pathExtension
    }

    /// Delete the last path component.
    var deletingLastPathComponent: String {
        NSString(string: self).deletingLastPathComponent
    }

    /// Delete the path extension.
    var deletingPathExtension: String {
        NSString(string: self).deletingPathExtension
    }

    /// Returns an array of path components.
    var pathComponents: [String] {
        NSString(string: self).pathComponents
    }
    
    /// Appends a path component to the string.
    ///
    /// - Parameter path: Path component to append.
    /// - Returns: Returns all the string.
    func appendingPathComponent(_ path: String) -&gt; String {
        let string = NSString(string: self)
        return string.appendingPathComponent(path)
    }
    
    /// Appends a path extension to the string.
    ///
    /// - Parameter ext: Extension to append.
    /// - Returns: Returns all the string.
    func appendingPathExtension(_ ext: String) -&gt; String? {
        let nsSt = NSString(string: self)
        return nsSt.appendingPathExtension(ext)
    }
    
    /// Converts self to an UUID APNS valid (No &quot;&lt;&gt;&quot; or &quot;-&quot; or spaces).
    ///
    /// - Returns: Converts self to an UUID APNS valid (No &quot;&lt;&gt;&quot; or &quot;-&quot; or spaces).
    func readableUUID() -&gt; String {
        trimmingCharacters(in: CharacterSet(charactersIn: &quot;&lt;&gt;&quot;)).replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;).replacingOccurrences(of: &quot;-&quot;, with: &quot;&quot;)
    }
    
    /// Returns string with the first character uppercased.
    ///
    /// - returns: Returns string with the first character uppercased.
    func uppercasedFirst() -&gt; String {
        String(prefix(1)).uppercased() + String(dropFirst())
    }
    
    /// Returns string with the first character lowercased.
    ///
    /// - returns: Returns string with the first character lowercased.
    func lowercasedFirst() -&gt; String {
        String(prefix(1)).lowercased() + String(dropFirst())
    }
    
    /// Returns the reversed String.
    ///
    /// - parameter preserveFormat: If set to true preserve the String format.
    ///                             The default value is false.
    ///                             **Example:**
    ///                                 &quot;Let's try this function?&quot; -&gt;
    ///                                 &quot;?noitcnuf siht yrt S'tel&quot;
    ///
    /// - returns: Returns the reversed String.
    func reversed(preserveFormat: Bool) -&gt; String {
        guard !isEmpty else {
            return &quot;&quot;
        }

        var reversed = String(removeExtraSpaces().reversed())

        guard preserveFormat else {
            return reversed
        }

        let words = reversed.components(separatedBy: &quot; &quot;).filter { !$0.isEmpty }

        reversed.removeAll()
        for word in words {
            if let char = word.unicodeScalars.last {
                if CharacterSet.uppercaseLetters.contains(char) {
                    reversed += word.lowercased().uppercasedFirst()
                } else {
                    reversed += word.lowercased()
                }
            } else {
                reversed += word.lowercased()
            }
            
            if word != words[words.count - 1] {
                reversed += &quot; &quot;
            }
        }

        return reversed
    }
    
    /// Returns true if the String has at least one uppercase chatacter, otherwise false.
    ///
    /// - returns: Returns true if the String has at least one uppercase chatacter, otherwise false.
    func hasUppercasedCharacters() -&gt; Bool {
        var found = false
        for character in unicodeScalars where CharacterSet.uppercaseLetters.contains(character) {
            found = true
        }
        return found
    }
    
    /// Returns true if the String has at least one lowercase chatacter, otherwise false.
    ///
    /// - returns: Returns true if the String has at least one lowercase chatacter, otherwise false.
    func hasLowercasedCharacters() -&gt; Bool {
        var found = false
        for character in unicodeScalars where CharacterSet.lowercaseLetters.contains(character) {
            found = true
        }
        return found
    }
    
    /// Remove double or more duplicated spaces.
    ///
    /// - returns: Remove double or more duplicated spaces.
    func removeExtraSpaces() -&gt; String {
        let squashed = replacingOccurrences(of: &quot;[ ]+&quot;, with: &quot; &quot;, options: .regularExpression, range: nil)
        return squashed.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
    
    /// Returns a new string in which all occurrences of a target strings in a specified range of the String are replaced by another given string.
    ///
    /// - Parameters:
    ///   - target: Target strings array.
    ///   - replacement: Replacement string.
    /// - Returns: Returns a new string in which all occurrences of a target strings in a specified range of the String are replaced by another given string.
    func replacingOccurrences(of target: [String], with replacement: String) -&gt; String {
        var string = self
        for occurrence in target {
            string = string.replacingOccurrences(of: occurrence, with: replacement)
        }
        
        return string
    }
    
    /// Count the number of lowercase characters.
    ///
    /// - Returns: Number of lowercase characters.
    func countLowercasedCharacters() -&gt; Int {
        var countLowercased = 0
        for char in self where char.isLowercase {
            countLowercased += 1
        }
        
        return countLowercased
    }
    
    /// Count the number of uppercase characters.
    ///
    /// - Returns: Number of uppercase characters.
    func countUppercasedCharacters() -&gt; Int {
        var countUppercased = 0
        for char in self where char.isUppercase {
            countUppercased += 1
        }
        
        return countUppercased
    }
    
    /// Count the number of numbers.
    ///
    /// - Returns: Number of numbers.
    func countNumbers() -&gt; Int {
        var countNumbers = 0
        for char in self where char.isNumber {
            countNumbers += 1
        }
        
        return countNumbers
    }
    
    /// Count the number of punctuations.
    ///
    /// - Returns: Number of punctuations.
    func countPunctuations() -&gt; Int {
        var countPuntuactions = 0
        for char in self where char.isPunctuation {
            countPuntuactions += 1
        }
        
        return countPuntuactions
    }
    
    /// Convert HEX string (separated by space) to &quot;usual&quot; characters string.
    /// Example: &quot;68 65 6c 6c 6f&quot; -&gt; &quot;hello&quot;.
    ///
    /// - Returns: Readable string.
    func stringFromHEX() -&gt; String {
        var hex = self
        var string: String = &quot;&quot;
        
        hex = hex.replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
        
        while !hex.isEmpty {
            let character = String(hex[..&lt;hex.index(hex.startIndex, offsetBy: 2)])
            var characterInt: UInt32 = 0
            
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...])
            _ = Scanner(string: character).scanHexInt32(&amp;characterInt)
            string += String(format: &quot;%c&quot;, characterInt)
        }
        return string
    }
    
    /// Return if self is anagram of another String.
    ///
    /// - Parameter string: Other String.
    /// - Returns: Return true if self is anagram of another String, otherwise false.
    func isAnagram(of string: String) -&gt; Bool {
        let lowerSelf = lowercased().replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
        let lowerOther = string.lowercased().replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
        return lowerSelf.sorted() == lowerOther.sorted()
    }
    
    /// Returns if self is palindrome.
    ///
    /// - Returns: Returns true if self is palindrome, otherwise false.
    func isPalindrome() -&gt; Bool {
        let selfString = lowercased().replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)
        let otherString = String(selfString.reversed())
        return selfString == otherString
    }
    
    /// Returns the character at the given index.
    ///
    /// - Parameter index: Returns the character at the given index.
    subscript(index: Int) -&gt; Character {
        self[self.index(startIndex, offsetBy: index)]
    }
    
    /// Returns the index of the given character, -1 if not found.
    ///
    /// - Parameter character: Returns the index of the given character, -1 if not found.
    subscript(character: Character) -&gt; Int {
        index(of: character)
    }
    
    /// Returns the character at the given index as String.
    ///
    /// - Parameter index: Returns the character at the given index as String.
    subscript(index: Int) -&gt; String {
        String(self[index])
    }
    
    /// Returns the string from a given range.
    /// Example: print(&quot;BFKit&quot;[1...3]) the result is &quot;FKi&quot;.
    ///
    /// - Parameter range: Returns the string from a given range.
    subscript(range: Range&lt;Int&gt;) -&gt; String {
        substring(with: range)
    }
    
    /// Returns if self is a valid UUID or not.
    ///
    /// - Returns: Returns if self is a valid UUID or not.
    func isUUID() -&gt; Bool {
        do {
            let regex: NSRegularExpression = try NSRegularExpression(pattern: &quot;^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$&quot;, options: .caseInsensitive)
            let matches: Int = regex.numberOfMatches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: count))
            return matches == 1
        } catch {
            return false
        }
    }
    
    /// Returns if self is a valid UUID for APNS (Apple Push Notification System) or not.
    ///
    /// - Returns: Returns if self is a valid UUID for APNS (Apple Push Notification System) or not.
    func isUUIDForAPNS() -&gt; Bool {
        do {
            let regex: NSRegularExpression = try NSRegularExpression(pattern: &quot;^[0-9a-f]{32}$&quot;, options: .caseInsensitive)
            let matches: Int = regex.numberOfMatches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: count))
            return matches == 1
        } catch {
            return false
        }
    }
    
    /// Returns a new string containing matching regular expressions replaced with the template string.
    ///
    /// - Parameters:
    ///   - regexString: The regex string.
    ///   - replacement: The replacement string.
    /// - Returns: Returns a new string containing matching regular expressions replaced with the template string.
    /// - Throws: Throws NSRegularExpression(pattern:, options:) errors.
    func replacingMatches(regex regexString: String, with replacement: String) throws -&gt; String {
        let regex: NSRegularExpression = try NSRegularExpression(pattern: regexString, options: .caseInsensitive)
        return regex.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: count), withTemplate: &quot;&quot;)
    }
    
    /// Localize current String using self as key.
    ///
    /// - Returns: Returns localized String using self as key.
    func localize() -&gt; String {
        NSLocalizedString(self, comment: &quot;&quot;)
    }
    
    // MARK: - Functions not available on Linux
    
    #if !os(Linux)
        /// Check if self is an email.
        ///
        /// - Returns: Returns true if it is an email, otherwise false.
        func isEmail() -&gt; Bool {
            let emailRegEx: String = &quot;^[a-zA-Z0-9.!#$%&amp;'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$&quot;
            
            let regExPredicate = NSPredicate(format: &quot;SELF MATCHES %@&quot;, emailRegEx)
            
            return regExPredicate.evaluate(with: lowercased())
        }
    
        /// Returns an array of String with all the links in 
        ///
        /// - Returns: Returns an array of String with all the links in 
        /// - Throws: Throws NSDataDetector errors.
        func links() throws -&gt; [String] {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
            
            let links = Array(detector.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: count)))
            
            return links.filter { $0.url != nil }.map { $0.url?.absoluteString ?? &quot;&quot; }
        }

        /// Returns an array of Date with all the dates in 
        ///
        /// - Returns: Returns an array of Date with all the date in 
        /// - Throws: Throws NSDataDetector errors.
        func dates() throws -&gt; [Date] {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
            
            let dates = Array(detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withTransparentBounds, range: NSRange(location: 0, length: count)))
            
            return dates.filter { $0.date != nil }.map { $0.date ?? Date() }
        }
    
        /// Returns an array of String with all the hashtags in 
        ///
        /// - Returns: Returns an array of String with all the hashtags in 
        /// - Throws: Throws NSRegularExpression errors.
        func hashtags() throws -&gt; [String] {
            let detector = try NSRegularExpression(pattern: &quot;#(\\w+)&quot;, options: NSRegularExpression.Options.caseInsensitive)
            let hashtags = Array(detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSRange(location: 0, length: count)))
            
            return hashtags.map { (self as NSString).substring(with: $0.range(at: 1)) }
        }
    
        /// Returns an array of String with all the mentions in 
        ///
        /// - Returns: Returns an array of String with all the mentions in 
        /// - Throws: Throws NSRegularExpression errors.
        func mentions() throws -&gt; [String] {
            let detector = try NSRegularExpression(pattern: &quot;@(\\w+)&quot;, options: NSRegularExpression.Options.caseInsensitive)
            let mentions = Array(detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSRange(location: 0, length: count)))
            
            return mentions.map { (self as NSString).substring(with: $0.range(at: 1)) }
        }
    #endif
}

/// Infix operator `???` with NilCoalescingPrecedence.
infix operator ???: NilCoalescingPrecedence

/// Returns defaultValue if optional is nil, otherwise returns optional.
///
/// - Parameters:
///   - optional: The optional variable.
///   - defaultValue: The default value.
/// - Returns: Returns defaultValue if optional is nil, otherwise returns optional.
public func ??? &lt;T&gt;(optional: T?, defaultValue: @autoclosure () -&gt; String) -&gt; String {
    optional.map { String(describing: $0) } ?? defaultValue()
}
</code></pre>
<h2 id="for-stringprotocol"><a class="header" href="#for-stringprotocol">for StringProtocol</a></h2>
<pre><code class="language-swift">
import Foundation

public extension StringProtocol {
    /// SwifterSwift: The longest common suffix.
    ///
    ///        &quot;Hello world!&quot;.commonSuffix(with: &quot;It's cold!&quot;) = &quot;ld!&quot;
    ///
    /// - Parameters:
    ///     - Parameter aString: The string with which to compare the receiver.
    ///     - Parameter options: Options for the comparison.
    /// - Returns: The longest common suffix of the receiver and the given String.
    func commonSuffix&lt;T: StringProtocol&gt;(with aString: T, options: String.CompareOptions = []) -&gt; String {
        return String(zip(reversed(), aString.reversed())
            .lazy
            .prefix(while: { (lhs: Character, rhs: Character) in
                String(lhs).compare(String(rhs), options: options) == .orderedSame
            })
            .map { (lhs: Character, _: Character) in lhs }
            .reversed())
    }

    #if canImport(Foundation)
    /// SwifterSwift: Returns a new string in which all occurrences of a regex pattern in a specified range of the receiver are replaced by the template.
    /// - Parameters:
    ///   - pattern: Regex pattern to replace.
    ///   - template: The regex template to replace the pattern.
    ///   - options: Options to use when matching the regex. Only .regularExpression, .anchored .and caseInsensitive are supported.
    ///   - searchRange: The range in the receiver in which to search.
    /// - Returns: A new string in which all occurrences of regex pattern in searchRange of the receiver are replaced by template.
    func replacingOccurrences&lt;Target, Replacement&gt;(
        ofPattern pattern: Target,
        withTemplate template: Replacement,
        options: String.CompareOptions = [.regularExpression],
        range searchRange: Range&lt;Self.Index&gt;? = nil) -&gt; String where Target: StringProtocol,
        Replacement: StringProtocol {
        assert(
            options.isStrictSubset(of: [.regularExpression, .anchored, .caseInsensitive]),
            &quot;Invalid options for regular expression replacement&quot;)
        return replacingOccurrences(
            of: pattern,
            with: template,
            options: options.union(.regularExpression),
            range: searchRange)
    }
    #endif
}
</code></pre>
<h2 id="for-array"><a class="header" href="#for-array">for Array</a></h2>
<pre><code class="language-swift">import Foundation

public extension Array{
    mutating func push(_ s:Element){
        self.append(s)
    }
    func len()-&gt;Int{
        self.count
    }
    mutating func pop()-&gt;Element?{
        self.popLast()
    }
    mutating func clear(){
        self = []
    }
    mutating func remove(_ index:Int)-&gt;Element{
        let val = self.remove(at: index)
        return val
    }
}
extension Array where Element: Equatable {
    mutating func dedup() {
        var result = [Element]()
        for element in self {
            if !result.contains(element) {
                result.append(element)
            }
        }
        self = result
    }
}



// MARK: - Global functions

/// Creates a flatten array.
///
/// Example:
///     [1, 2, [3, [4]]] -&gt; [1, 2, 3, 4]
/// - Parameter array: Array bo te flattened.
/// - Returns: Returns a flatten array.
public func flatten&lt;T&gt;(_ array: [T]) -&gt; [T] {
    /// Returned flattened array.
    var flattened: [T] = []
    /// For every element inside the array.
    for element in array {
        /// If it's a nested array, safely cast.
        if let subarray = element as? [T] {
            /// For every subarray call the `flatten` function.
            for subelement in flatten(subarray) {
                /// We are now sure that this is an element
                /// and we can add it to `flattened`.
                flattened.append(subelement)
            }
        } else {
            /// Otherwise is an element and add it to `flattened`.
            flattened.append(element)
        }
    }
    
    return flattened
}


extension Array {
    mutating func shuffleArray() {
        for i in 0 ..&lt; (count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            swapAt(i, j)
        }
    }
}

/// This extension adds some useful functions to Array.
public extension Array {
    // MARK: - Functions
    
    /// A Bool value indicating whether the collection is not empty.
    ///
    /// - Returns: Returns a Bool value indicating whether the collection is not empty.
    var isNotEmpty: Bool {
        !isEmpty
    }
    
    /// Simulates the array as a circle. When it is out of range, begins again.
    ///
    /// - Parameter index: The index.
    /// - Returns: Returns the object at a given index.
    func circleObject(at index: Int) -&gt; Element {
        self[superCircle(at: index, size: count)]
    }
    
    /// Randomly selects an element from self and returns it.
    ///
    /// - returns: An element that was randomly selected from the array.
    func random() -&gt; Element {
        self[Int.random(in: 0...count - 1)]
    }
    
    /// Removes the element from self that is passed in.
    /// 
    /// - parameter object: The element that is removed from 
    mutating func remove(_ object: Element) {
        var array: [String] = []
        for index in self {
            array.append(&quot;\(index)&quot;)
        }
        let index = array.firstIndex(of: &quot;\(object)&quot;)
        if let index = index {
            remove(at: index)
        }
    }
    
    /// Get the object at a given index in safe mode (nil if self is empty or out of range).
    ///
    /// - Parameter index: The index.
    /// - Returns: Returns the object at a given index in safe mode (nil if self is empty or out of range).
    func safeObject(at index: Int) -&gt; Element? {
        guard !isEmpty, count &gt; index else {
            return nil
        }
        
        return self[index]
    }
    
    /// Get the index as a circle.
    ///
    /// - Parameters:
    ///   - index: The index.
    ///   - maxSize: Max size of the array.
    /// - Returns: Returns the right index.
    private func superCircle(at index: Int, size maxSize: Int) -&gt; Int {
        var newIndex = index
        if newIndex &lt; 0 {
            newIndex = newIndex % maxSize
            newIndex += maxSize
        }
        if newIndex &gt;= maxSize {
            newIndex = newIndex % maxSize
        }
        
        return newIndex
    }
    
    /// Move object from an index to another.
    ///
    /// - Parameters:
    ///   - fromIndex: The start index.
    ///   - toIndex: The end index.
    mutating func swap(from fromIndex: Int, to toIndex: Int) {
        if toIndex != fromIndex {
            guard let object: Element = safeObject(at: fromIndex) else {
                return
            }
            remove(at: fromIndex)
            
            if toIndex &gt;= count {
                append(object)
            } else {
                insert(object, at: toIndex)
            }
        }
    }
}


// MARK: - Initializers
public extension Array {
    /// SwifterSwift: Creates an array with specified number of elements, for each element it calls specified closure.
    /// - Parameters:
    ///   - count: The number of elements in the new array.
    ///   - element: A closure that initializes each element.
    ///     - Parameter *index*: An index of initialized element in the array.
    ///     - Returns: element of the array.
    init(count: Int, element: (Int) throws -&gt; Element) rethrows {
        try self.init(unsafeUninitializedCapacity: count) { buffer, initializedCount in
            for index in 0..&lt;count {
                try buffer.baseAddress?.advanced(by: index).initialize(to: element(index))
            }
            initializedCount = count
        }
    }
}

// MARK: - Methods

public extension Array {
    /// SwifterSwift: Insert an element at the beginning of array.
    ///
    ///        [2, 3, 4, 5].prepend(1) -&gt; [1, 2, 3, 4, 5]
    ///        [&quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].prepend(&quot;h&quot;) -&gt; [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]
    ///
    /// - Parameter newElement: element to insert.
    mutating func prepend(_ newElement: Element) {
        insert(newElement, at: 0)
    }

    /// SwifterSwift: Safely swap values at given index positions.
    ///
    ///        [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -&gt; [4, 2, 3, 1, 5]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].safeSwap(from: 1, to: 0) -&gt; [&quot;e&quot;, &quot;h&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]
    ///
    /// - Parameters:
    ///   - index: index of first element.
    ///   - otherIndex: index of other element.
    mutating func safeSwap(from index: Index, to otherIndex: Index) {
        guard index != otherIndex else { return }
        guard startIndex..&lt;endIndex ~= index else { return }
        guard startIndex..&lt;endIndex ~= otherIndex else { return }
        swapAt(index, otherIndex)
    }

    /// SwifterSwift: Sort an array like another array based on a key path. If the other array doesn't contain a certain value, it will be sorted last.
    ///
    ///        [MyStruct(x: 3), MyStruct(x: 1), MyStruct(x: 2)].sorted(like: [1, 2, 3], keyPath: \.x)
    ///            -&gt; [MyStruct(x: 1), MyStruct(x: 2), MyStruct(x: 3)]
    ///
    /// - Parameters:
    ///   - otherArray: array containing elements in the desired order.
    ///   - keyPath: keyPath indicating the property that the array should be sorted by
    /// - Returns: sorted array.
    func sorted&lt;T: Hashable&gt;(like otherArray: [T], keyPath: KeyPath&lt;Element, T&gt;) -&gt; [Element] {
        let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
        return sorted {
            guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false }
            guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true }
            return thisIndex &lt; otherIndex
        }
    }
}

// MARK: - Methods (Equatable)

public extension Array where Element: Equatable {
    /// SwifterSwift: Remove all instances of an item from array.
    ///
    ///        [1, 2, 2, 3, 4, 5].removeAll(2) -&gt; [1, 3, 4, 5]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].removeAll(&quot;l&quot;) -&gt; [&quot;h&quot;, &quot;e&quot;, &quot;o&quot;]
    ///
    /// - Parameter item: item to remove.
    /// - Returns: self after removing all instances of item.
    @discardableResult
    mutating func removeAll(_ item: Element) -&gt; [Element] {
        removeAll(where: { $0 == item })
        return self
    }

    /// SwifterSwift: Remove all instances contained in items parameter from array.
    ///
    ///        [1, 2, 2, 3, 4, 5].removeAll([2,5]) -&gt; [1, 3, 4]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].removeAll([&quot;l&quot;, &quot;h&quot;]) -&gt; [&quot;e&quot;, &quot;o&quot;]
    ///
    /// - Parameter items: items to remove.
    /// - Returns: self after removing all instances of all items in given array.
    @discardableResult
    mutating func removeAll(_ items: [Element]) -&gt; [Element] {
        guard !items.isEmpty else { return self }
        removeAll(where: { items.contains($0) })
        return self
    }

    /// SwifterSwift: Remove all duplicate elements from Array.
    ///
    ///        [1, 2, 2, 3, 4, 5].removeDuplicates() -&gt; [1, 2, 3, 4, 5]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]. removeDuplicates() -&gt; [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;o&quot;]
    ///
    /// - Returns: Return array with all duplicate elements removed.
    @discardableResult
    mutating func removeDuplicates() -&gt; [Element] {
        // Thanks to https://github.com/sairamkotha for improving the method
        self = reduce(into: [Element]()) {
            if !$0.contains($1) {
                $0.append($1)
            }
        }
        return self
    }

    /// SwifterSwift: Return array with all duplicate elements removed.
    ///
    ///     [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -&gt; [1, 2, 3, 4, 5])
    ///     [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].withoutDuplicates() -&gt; [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;o&quot;])
    ///
    /// - Returns: an array of unique elements.
    ///
    func withoutDuplicates() -&gt; [Element] {
        // Thanks to https://github.com/sairamkotha for improving the method
        return reduce(into: [Element]()) {
            if !$0.contains($1) {
                $0.append($1)
            }
        }
    }

    /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
    ///
    /// - Parameter path: Key path to compare, the value must be Equatable.
    /// - Returns: an array of unique elements.
    func withoutDuplicates&lt;E: Equatable&gt;(keyPath path: KeyPath&lt;Element, E&gt;) -&gt; [Element] {
        return reduce(into: [Element]()) { result, element in
            if !result.contains(where: { $0[keyPath: path] == element[keyPath: path] }) {
                result.append(element)
            }
        }
    }

    /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
    ///
    /// - Parameter path: Key path to compare, the value must be Hashable.
    /// - Returns: an array of unique elements.
    func withoutDuplicates&lt;E: Hashable&gt;(keyPath path: KeyPath&lt;Element, E&gt;) -&gt; [Element] {
        var set = Set&lt;E&gt;()
        return filter { set.insert($0[keyPath: path]).inserted }
    }
}

</code></pre>
<h2 id="for-optional"><a class="header" href="#for-optional">for Optional</a></h2>
<pre><code class="language-swift">import Foundation

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public extension Optional where Wrapped: Collection {
    /// Returns whether the instance is nil or empty.
    @inlinable var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

public extension Optional {
    /// SwifterSwift: Get self of default value (if self is nil).
    ///
    ///		let foo: String? = nil
    ///		print(foo.unwrapped(or: &quot;bar&quot;)) -&gt; &quot;bar&quot;
    ///
    ///		let bar: String? = &quot;bar&quot;
    ///		print(bar.unwrapped(or: &quot;foo&quot;)) -&gt; &quot;bar&quot;
    ///
    /// - Parameter defaultValue: default value to return if self is nil.
    /// - Returns: self if not nil or default value if nil.
    func unwrapped(or defaultValue: Wrapped) -&gt; Wrapped {
        // http://www.russbishop.net/improving-optionals
        return self ?? defaultValue
    }

    /// SwifterSwift: Gets the wrapped value of an optional. If the optional is `nil`, throw a custom error.
    ///
    ///        let foo: String? = nil
    ///        try print(foo.unwrapped(or: MyError.notFound)) -&gt; error: MyError.notFound
    ///
    ///        let bar: String? = &quot;bar&quot;
    ///        try print(bar.unwrapped(or: MyError.notFound)) -&gt; &quot;bar&quot;
    ///
    /// - Parameter error: The error to throw if the optional is `nil`.
    /// - Throws: The error passed in.
    /// - Returns: The value wrapped by the optional.
    func unwrapped(or error: Error) throws -&gt; Wrapped {
        guard let wrapped = self else { throw error }
        return wrapped
    }

    /// SwifterSwift: Runs a block to Wrapped if not nil.
    ///
    ///		let foo: String? = nil
    ///		foo.run { unwrappedFoo in
    ///			// block will never run since foo is nil
    ///			print(unwrappedFoo)
    ///		}
    ///
    ///		let bar: String? = &quot;bar&quot;
    ///		bar.run { unwrappedBar in
    ///			// block will run since bar is not nil
    ///			print(unwrappedBar) -&gt; &quot;bar&quot;
    ///		}
    ///
    /// - Parameter block: a block to run if self is not nil.
    func run(_ block: (Wrapped) -&gt; Void) {
        // http://www.russbishop.net/improving-optionals
        _ = map(block)
    }

    /// SwifterSwift: Assign an optional value to a variable only if the value is not nil.
    ///
    ///     let someParameter: String? = nil
    ///     let parameters = [String: Any]() // Some parameters to be attached to a GET request
    ///     parameters[someKey] ??= someParameter // It won't be added to the parameters dict
    ///
    /// - Parameters:
    ///   - lhs: Any?
    ///   - rhs: Any?
    static func ??= (lhs: inout Optional, rhs: Optional) {
        guard let rhs = rhs else { return }
        lhs = rhs
    }

    /// SwifterSwift: Assign an optional value to a variable only if the variable is nil.
    ///
    ///     var someText: String? = nil
    ///     let newText = &quot;Foo&quot;
    ///     let defaultText = &quot;Bar&quot;
    ///     someText ?= newText // someText is now &quot;Foo&quot; because it was nil before
    ///     someText ?= defaultText // someText doesn't change its value because it's not nil
    ///
    /// - Parameters:
    ///   - lhs: Any?
    ///   - rhs: Any?
    static func ?= (lhs: inout Optional, rhs: @autoclosure () -&gt; Optional) {
        if lhs == nil {
            lhs = rhs()
        }
    }
}

// MARK: - Methods (Collection)

public extension Optional where Wrapped: Collection {
    /// SwifterSwift: Check if optional is nil or empty collection.
    var isNilOrEmpty: Bool {
        guard let collection = self else { return true }
        return collection.isEmpty
    }

    /// SwifterSwift: Returns the collection only if it is not nil and not empty.
    var nonEmpty: Wrapped? {
        guard let collection = self else { return nil }
        guard !collection.isEmpty else { return nil }
        return collection
    }
}

// MARK: - Methods (RawRepresentable, RawValue: Equatable)

public extension Optional where Wrapped: RawRepresentable, Wrapped.RawValue: Equatable {
    // swiftlint:disable missing_swifterswift_prefix

    /// Returns a Boolean value indicating whether two values are equal.
    ///
    /// Equality is the inverse of inequality. For any values `a` and `b`,
    /// `a == b` implies that `a != b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    @inlinable static func == (lhs: Optional, rhs: Wrapped.RawValue?) -&gt; Bool {
        return lhs?.rawValue == rhs
    }

    /// Returns a Boolean value indicating whether two values are equal.
    ///
    /// Equality is the inverse of inequality. For any values `a` and `b`,
    /// `a == b` implies that `a != b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    @inlinable static func == (lhs: Wrapped.RawValue?, rhs: Optional) -&gt; Bool {
        return lhs == rhs?.rawValue
    }

    /// Returns a Boolean value indicating whether two values are not equal.
    ///
    /// Inequality is the inverse of equality. For any values `a` and `b`,
    /// `a != b` implies that `a == b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    @inlinable static func != (lhs: Optional, rhs: Wrapped.RawValue?) -&gt; Bool {
        return lhs?.rawValue != rhs
    }

    /// Returns a Boolean value indicating whether two values are not equal.
    ///
    /// Inequality is the inverse of equality. For any values `a` and `b`,
    /// `a != b` implies that `a == b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    @inlinable static func != (lhs: Wrapped.RawValue?, rhs: Optional) -&gt; Bool {
        return lhs != rhs?.rawValue
    }

    // swiftlint:enable missing_swifterswift_prefix
}

// MARK: - Operators

infix operator ??=: AssignmentPrecedence
infix operator ?=: AssignmentPrecedence
</code></pre>
<h2 id="for-result"><a class="header" href="#for-result">for Result</a></h2>
<pre><code class="language-swift">
import Foundation

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public extension Result {
    /// Returns whether the instance is `.success`.
    @inlinable var isSuccess: Bool {
        guard case .success = self else { return false }
        return true
    }

    /// Returns whether the instance is `.failure`.
    @inlinable var isFailure: Bool {
        !isSuccess
    }

    /// Returns the associated value if the result is a success, `nil` otherwise.
    @inlinable var success: Success? {
        guard case let .success(value) = self else { return nil }
        return value
    }

    /// Returns the associated error value if the result is a failure, `nil` otherwise.
    @inlinable var failure: Failure? {
        guard case let .failure(error) = self else { return nil }
        return error
    }

    /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise.
    ///
    /// - Parameters:
    ///   - value: A value.
    ///   - error: An `Error`.
    @inlinable init(value: Success, error: Failure?) {
        if let error = error {
            self = .failure(error)
        } else {
            self = .success(value)
        }
    }

    /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
    ///
    /// Use the `tryMap` method with a closure that may throw an error. For example:
    ///
    ///     let possibleData: Result&lt;Data, Error&gt; = .success(Data(...))
    ///     let possibleObject = possibleData.tryMap {
    ///         try JSONSerialization.jsonObject(with: $0)
    ///     }
    ///
    /// - parameter transform: A closure that takes the success value of the instance.
    ///
    /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the
    ///            same failure.
    @inlinable func tryMap&lt;NewSuccess&gt;(_ transform: (Success) throws -&gt; NewSuccess) -&gt; Result&lt;NewSuccess, Error&gt; {
        switch self {
        case let .success(value):
            do {
                return try .success(transform(value))
            } catch {
                return .failure(error)
            }
        case let .failure(error):
            return .failure(error)
        }
    }

    /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
    ///
    /// Use the `tryMapError` function with a closure that may throw an error. For example:
    ///
    ///     let possibleData: Result&lt;Data, Error&gt; = .success(Data(...))
    ///     let possibleObject = possibleData.tryMapError {
    ///         try someFailableFunction(taking: $0)
    ///     }
    ///
    /// - Parameter transform: A throwing closure that takes the error of the instance.
    ///
    /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns
    ///            the same success.
    @inlinable func tryMapError&lt;NewFailure: Error&gt;(
        _ transform: (Failure) throws -&gt; NewFailure
    ) -&gt; Result&lt;Success, Error&gt; {
        switch self {
        case let .failure(error):
            do {
                return try .failure(transform(error))
            } catch {
                return .failure(error)
            }
        case let .success(value):
            return .success(value)
        }
    }
}
</code></pre>
<h2 id="for-url"><a class="header" href="#for-url">for URL</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation

#if canImport(UIKit) &amp;&amp; canImport(AVFoundation)
import AVFoundation
import UIKit
#endif

// MARK: - Properties

public extension URL {
    /// SwifterSwift: Dictionary of the URL's query parameters.
    var queryParameters: [String: String]? {
        guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
              let queryItems = components.queryItems else { return nil }

        var items: [String: String] = [:]

        for queryItem in queryItems {
            items[queryItem.name] = queryItem.value
        }

        return items
    }
}

// MARK: - Initializers

public extension URL {
    /// SwifterSwift: Initializes an `URL` object with a base URL and a relative string. If `string` was malformed, returns `nil`.
    /// - Parameters:
    ///   - string: The URL string with which to initialize the `URL` object. Must conform to RFC 2396. `string` is interpreted relative to `url`.
    ///   - url: The base URL for the `URL` object.
    init?(string: String?, relativeTo url: URL? = nil) {
        guard let string = string else { return nil }
        self.init(string: string, relativeTo: url)
    }

    /**
     SwifterSwift: Initializes a forced unwrapped `URL` from string. Can potentially crash if string is invalid.
      - Parameter unsafeString: The URL string used to initialize the `URL`object.
      */
    init(unsafeString: String) {
        self.init(string: unsafeString)!
    }
}

// MARK: - Methods

public extension URL {
    /// SwifterSwift: URL with appending query parameters.
    ///
    ///		let url = URL(string: &quot;https://google.com&quot;)!
    ///		let param = [&quot;q&quot;: &quot;Swifter Swift&quot;]
    ///		url.appendingQueryParameters(params) -&gt; &quot;https://google.com?q=Swifter%20Swift&quot;
    ///
    /// - Parameter parameters: parameters dictionary.
    /// - Returns: URL with appending given query parameters.
    func appendingQueryParameters(_ parameters: [String: String]) -&gt; URL {
        var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
        urlComponents.queryItems = (urlComponents.queryItems ?? []) + parameters
            .map { URLQueryItem(name: $0, value: $1) }
        return urlComponents.url!
    }

    /// SwifterSwift: Append query parameters to URL.
    ///
    ///		var url = URL(string: &quot;https://google.com&quot;)!
    ///		let param = [&quot;q&quot;: &quot;Swifter Swift&quot;]
    ///		url.appendQueryParameters(params)
    ///		print(url) // prints &quot;https://google.com?q=Swifter%20Swift&quot;
    ///
    /// - Parameter parameters: parameters dictionary.
    mutating func appendQueryParameters(_ parameters: [String: String]) {
        self = appendingQueryParameters(parameters)
    }

    /// SwifterSwift: Get value of a query key.
    ///
    ///    var url = URL(string: &quot;https://google.com?code=12345&quot;)!
    ///    queryValue(for: &quot;code&quot;) -&gt; &quot;12345&quot;
    ///
    /// - Parameter key: The key of a query value.
    func queryValue(for key: String) -&gt; String? {
        return URLComponents(string: absoluteString)?
            .queryItems?
            .first(where: { $0.name == key })?
            .value
    }

    /// SwifterSwift: Returns a new URL by removing all the path components.
    ///
    ///     let url = URL(string: &quot;https://domain.com/path/other&quot;)!
    ///     print(url.deletingAllPathComponents()) // prints &quot;https://domain.com/&quot;
    ///
    /// - Returns: URL with all path components removed.
    func deletingAllPathComponents() -&gt; URL {
        guard !pathComponents.isEmpty else { return self }

        var url: URL = self
        for _ in 0..&lt;pathComponents.count - 1 {
            url.deleteLastPathComponent()
        }
        return url
    }

    /// SwifterSwift: Remove all the path components from the URL.
    ///
    ///        var url = URL(string: &quot;https://domain.com/path/other&quot;)!
    ///        url.deleteAllPathComponents()
    ///        print(url) // prints &quot;https://domain.com/&quot;
    mutating func deleteAllPathComponents() {
        guard !pathComponents.isEmpty else { return }

        for _ in 0..&lt;pathComponents.count - 1 {
            deleteLastPathComponent()
        }
    }

    /// SwifterSwift: Generates new URL that does not have scheme.
    ///
    ///        let url = URL(string: &quot;https://domain.com&quot;)!
    ///        print(url.droppedScheme()) // prints &quot;domain.com&quot;
    func droppedScheme() -&gt; URL? {
        if let scheme = scheme {
            let droppedScheme = String(absoluteString.dropFirst(scheme.count + 3))
            return URL(string: droppedScheme)
        }

        guard host != nil else { return self }

        let droppedScheme = String(absoluteString.dropFirst(2))
        return URL(string: droppedScheme)
    }
}

// MARK: - Methods

public extension URL {
    #if os(iOS) || os(tvOS)
    /// SwifterSwift: Generate a thumbnail image from given url. Returns nil if no thumbnail could be created. This function may take some time to complete. It's recommended to dispatch the call if the thumbnail is not generated from a local resource.
    ///
    ///     var url = URL(string: &quot;https://video.golem.de/files/1/1/20637/wrkw0718-sd.mp4&quot;)!
    ///     var thumbnail = url.thumbnail()
    ///     thumbnail = url.thumbnail(fromTime: 5)
    ///
    ///     DispatchQueue.main.async {
    ///         someImageView.image = url.thumbnail()
    ///     }
    ///
    /// - Parameter time: Seconds into the video where the image should be generated.
    /// - Returns: The UIImage result of the AVAssetImageGenerator
    func thumbnail(fromTime time: Float64 = 0) -&gt; UIImage? {
        let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self))
        let time = CMTimeMakeWithSeconds(time, preferredTimescale: 1)
        var actualTime = CMTimeMake(value: 0, timescale: 0)

        guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &amp;actualTime) else {
            return nil
        }
        return UIImage(cgImage: cgImage)
    }
    #endif
}

#endif
</code></pre>
<h2 id="for-cryptokit-digest"><a class="header" href="#for-cryptokit-digest">for CryptoKit Digest</a></h2>
<pre><code class="language-swift">
#if canImport(CryptoKit)
import CryptoKit

@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
public extension Digest {

    // MARK: - Properties

    /// SwifterSwift: Hexadecimal value string (read-only, Complexity: O(N), _N_ being the amount of bytes.)
    var hexString: String {
        var result = &quot;&quot;
        for byte in self.makeIterator() {
            result += String(format: &quot;%02X&quot;, byte)
        }
        return result
    }
}
#endif

</code></pre>
<h2 id="for-sequence"><a class="header" href="#for-sequence">for Sequence</a></h2>
<pre><code class="language-swift">
public extension Sequence {
    /// SwifterSwift: Check if all elements in collection match a condition.
    ///
    ///        [2, 2, 4].all(matching: {$0 % 2 == 0}) -&gt; true
    ///        [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -&gt; false
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: true when all elements in the array match the specified condition.
    func all(matching condition: (Element) throws -&gt; Bool) rethrows -&gt; Bool {
        return try !contains { try !condition($0) }
    }

    /// SwifterSwift: Check if no elements in collection match a condition.
    ///
    ///        [2, 2, 4].none(matching: {$0 % 2 == 0}) -&gt; false
    ///        [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -&gt; true
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: true when no elements in the array match the specified condition.
    func none(matching condition: (Element) throws -&gt; Bool) rethrows -&gt; Bool {
        return try !contains { try condition($0) }
    }

    /// SwifterSwift: Check if any element in collection match a condition.
    ///
    ///        [2, 2, 4].any(matching: {$0 % 2 == 0}) -&gt; false
    ///        [1, 3, 5, 7].any(matching: {$0 % 2 == 0}) -&gt; true
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: true when no elements in the array match the specified condition.
    func any(matching condition: (Element) throws -&gt; Bool) rethrows -&gt; Bool {
        return try contains { try condition($0) }
    }

    /// SwifterSwift: Filter elements based on a rejection condition.
    ///
    ///        [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -&gt; [7]
    ///
    /// - Parameter condition: to evaluate the exclusion of an element from the array.
    /// - Returns: the array with rejected values filtered from it.
    func reject(where condition: (Element) throws -&gt; Bool) rethrows -&gt; [Element] {
        return try filter { return try !condition($0) }
    }

    /// SwifterSwift: Get element count based on condition.
    ///
    ///        [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -&gt; 3
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: number of times the condition evaluated to true.
    func count(where condition: (Element) throws -&gt; Bool) rethrows -&gt; Int {
        var count = 0
        for element in self where try condition(element) {
            count += 1
        }
        return count
    }

    /// SwifterSwift: Iterate over a collection in reverse order. (right to left)
    ///
    ///        [0, 2, 4, 7].forEachReversed({ print($0)}) -&gt; // Order of print: 7,4,2,0
    ///
    /// - Parameter body: a closure that takes an element of the array as a parameter.
    func forEachReversed(_ body: (Element) throws -&gt; Void) rethrows {
        try reversed().forEach(body)
    }

    /// SwifterSwift: Calls the given closure with each element where condition is true.
    ///
    ///        [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -&gt; // print: 0, 2, 4
    ///
    /// - Parameters:
    ///   - condition: condition to evaluate each element against.
    ///   - body: a closure that takes an element of the array as a parameter.
    func forEach(where condition: (Element) throws -&gt; Bool, body: (Element) throws -&gt; Void) rethrows {
        try lazy.filter(condition).forEach(body)
    }

    /// SwifterSwift: Reduces an array while returning each interim combination.
    ///
    ///     [1, 2, 3].accumulate(initial: 0, next: +) -&gt; [1, 3, 6]
    ///
    /// - Parameters:
    ///   - initial: initial value.
    ///   - next: closure that combines the accumulating value and next element of the array.
    /// - Returns: an array of the final accumulated value and each interim combination.
    func accumulate&lt;U&gt;(initial: U, next: (U, Element) throws -&gt; U) rethrows -&gt; [U] {
        var runningTotal = initial
        return try map { element in
            runningTotal = try next(runningTotal, element)
            return runningTotal
        }
    }

    /// SwifterSwift: Filtered and map in a single operation.
    ///
    ///     [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -&gt; [&quot;2&quot;, &quot;4&quot;]
    ///
    /// - Parameters:
    ///   - isIncluded: condition of inclusion to evaluate each element against.
    ///   - transform: transform element function to evaluate every element.
    /// - Returns: Return an filtered and mapped array.
    func filtered&lt;T&gt;(_ isIncluded: (Element) throws -&gt; Bool, map transform: (Element) throws -&gt; T) rethrows -&gt; [T] {
        return try lazy.filter(isIncluded).map(transform)
    }

    /// SwifterSwift: Get the only element based on a condition.
    ///
    ///     [].single(where: {_ in true}) -&gt; nil
    ///     [4].single(where: {_ in true}) -&gt; 4
    ///     [1, 4, 7].single(where: {$0 % 2 == 0}) -&gt; 4
    ///     [2, 2, 4, 7].single(where: {$0 % 2 == 0}) -&gt; nil
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: The only element in the array matching the specified condition. If there are more matching elements,
    /// nil is returned. (optional)
    func single(where condition: (Element) throws -&gt; Bool) rethrows -&gt; Element? {
        var singleElement: Element?
        for element in self where try condition(element) {
            guard singleElement == nil else {
                singleElement = nil
                break
            }
            singleElement = element
        }
        return singleElement
    }

    /// SwifterSwift: Remove duplicate elements based on condition.
    ///
    ///        [1, 2, 1, 3, 2].withoutDuplicates { $0 } -&gt; [1, 2, 3]
    ///        [(1, 4), (2, 2), (1, 3), (3, 2), (2, 1)].withoutDuplicates { $0.0 } -&gt; [(1, 4), (2, 2), (3, 2)]
    ///
    /// - Parameter transform: A closure that should return the value to be evaluated for repeating elements.
    /// - Returns: Sequence without repeating elements
    /// - Complexity: O(*n*), where *n* is the length of the sequence.
    func withoutDuplicates&lt;T: Hashable&gt;(transform: (Element) throws -&gt; T) rethrows -&gt; [Element] {
        var set = Set&lt;T&gt;()
        return try filter { set.insert(try transform($0)).inserted }
    }

    ///  SwifterSwift: Separates all items into 2 lists based on a given predicate. The first list contains all items
    /// for which the specified condition evaluates to true. The second list contains those that don't.
    ///
    ///     let (even, odd) = [0, 1, 2, 3, 4, 5].divided { $0 % 2 == 0 }
    ///     let (minors, adults) = people.divided { $0.age &lt; 18 }
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: A tuple of matched and non-matched items
    func divided(by condition: (Element) throws -&gt; Bool) rethrows -&gt; (matching: [Element], nonMatching: [Element]) {
        // Inspired by: http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-partition
        var matching = [Element]()
        var nonMatching = [Element]()

        for element in self {
            // swiftlint:disable:next void_function_in_ternary
            try condition(element) ? matching.append(element) : nonMatching.append(element)
        }
        return (matching, nonMatching)
    }

    /// SwifterSwift: Return a sorted array based on a key path and a compare function.
    ///
    /// - Parameter keyPath: Key path to sort by.
    /// - Parameter compare: Comparison function that will determine the ordering.
    /// - Returns: The sorted array.
    func sorted&lt;T&gt;(by keyPath: KeyPath&lt;Element, T&gt;, with compare: (T, T) -&gt; Bool) -&gt; [Element] {
        return sorted { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }

    /// SwifterSwift: Return a sorted array based on a key path.
    ///
    /// - Parameter keyPath: Key path to sort by. The key path type must be Comparable.
    /// - Returns: The sorted array.
    func sorted&lt;T: Comparable&gt;(by keyPath: KeyPath&lt;Element, T&gt;) -&gt; [Element] {
        return sorted { $0[keyPath: keyPath] &lt; $1[keyPath: keyPath] }
    }

    /// SwifterSwift: Returns a sorted sequence based on two key paths. The second one will be used in case the values
    /// of the first one match.
    ///
    /// - Parameters:
    ///     - keyPath1: Key path to sort by. Must be Comparable.
    ///     - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
    func sorted&lt;T: Comparable, U: Comparable&gt;(by keyPath1: KeyPath&lt;Element, T&gt;,
                                              and keyPath2: KeyPath&lt;Element, U&gt;) -&gt; [Element] {
        return sorted {
            if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
                return $0[keyPath: keyPath1] &lt; $1[keyPath: keyPath1]
            }
            return $0[keyPath: keyPath2] &lt; $1[keyPath: keyPath2]
        }
    }

    /// SwifterSwift: Returns a sorted sequence based on three key paths. Whenever the values of one key path match, the
    /// next one will be used.
    ///
    /// - Parameters:
    ///     - keyPath1: Key path to sort by. Must be Comparable.
    ///     - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
    ///     - keyPath3: Key path to sort by in case the values of `keyPath1` and `keyPath2` match. Must be Comparable.
    func sorted&lt;T: Comparable, U: Comparable, V: Comparable&gt;(by keyPath1: KeyPath&lt;Element, T&gt;,
                                                             and keyPath2: KeyPath&lt;Element, U&gt;,
                                                             and keyPath3: KeyPath&lt;Element, V&gt;) -&gt; [Element] {
        return sorted {
            if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
                return $0[keyPath: keyPath1] &lt; $1[keyPath: keyPath1]
            }
            if $0[keyPath: keyPath2] != $1[keyPath: keyPath2] {
                return $0[keyPath: keyPath2] &lt; $1[keyPath: keyPath2]
            }
            return $0[keyPath: keyPath3] &lt; $1[keyPath: keyPath3]
        }
    }

    /// SwifterSwift: Sum of a `AdditiveArithmetic` property of each `Element` in a `Sequence`.
    ///
    ///     [&quot;James&quot;, &quot;Wade&quot;, &quot;Bryant&quot;].sum(for: \.count) -&gt; 15
    ///
    /// - Parameter keyPath: Key path of the `AdditiveArithmetic` property.
    /// - Returns: The sum of the `AdditiveArithmetic` properties at `keyPath`.
    func sum&lt;T: AdditiveArithmetic&gt;(for keyPath: KeyPath&lt;Element, T&gt;) -&gt; T {
        // Inspired by: https://swiftbysundell.com/articles/reducers-in-swift/
        return reduce(.zero) { $0 + $1[keyPath: keyPath] }
    }

    /// SwifterSwift: Returns the first element of the sequence with having property by given key path equals to given
    /// `value`.
    ///
    /// - Parameters:
    ///   - keyPath: The `KeyPath` of property for `Element` to compare.
    ///   - value: The value to compare with `Element` property.
    /// - Returns: The first element of the collection that has property by given key path equals to given `value` or
    /// `nil` if there is no such element.
    func first&lt;T: Equatable&gt;(where keyPath: KeyPath&lt;Element, T&gt;, equals value: T) -&gt; Element? {
        return first { $0[keyPath: keyPath] == value }
    }
}

public extension Sequence where Element: Equatable {
    /// SwifterSwift: Check if array contains an array of elements.
    ///
    ///        [1, 2, 3, 4, 5].contains([1, 2]) -&gt; true
    ///        [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -&gt; false
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].contains([&quot;l&quot;, &quot;o&quot;]) -&gt; true
    ///
    /// - Parameter elements: array of elements to check.
    /// - Returns: true if array contains all given items.
    /// - Complexity: _O(m·n)_, where _m_ is the length of `elements` and _n_ is the length of this sequence.
    func contains(_ elements: [Element]) -&gt; Bool {
        return elements.allSatisfy { contains($0) }
    }
}

public extension Sequence where Element: Hashable {
    /// SwifterSwift: Check if array contains an array of elements.
    ///
    ///        [1, 2, 3, 4, 5].contains([1, 2]) -&gt; true
    ///        [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -&gt; false
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].contains([&quot;l&quot;, &quot;o&quot;]) -&gt; true
    ///
    /// - Parameter elements: array of elements to check.
    /// - Returns: true if array contains all given items.
    /// - Complexity: _O(m + n)_, where _m_ is the length of `elements` and _n_ is the length of this sequence.
    func contains(_ elements: [Element]) -&gt; Bool {
        let set = Set(self)
        return elements.allSatisfy { set.contains($0) }
    }

    /// SwifterSwift: Check whether a sequence contains duplicates.
    ///
    /// - Returns: true if the receiver contains duplicates.
    func containsDuplicates() -&gt; Bool {
        var set = Set&lt;Element&gt;()
        return contains { !set.insert($0).inserted }
    }

    /// SwifterSwift: Getting the duplicated elements in a sequence.
    ///
    ///     [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicates().sorted() -&gt; [1, 2, 3])
    ///     [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].duplicates().sorted() -&gt; [&quot;l&quot;])
    ///
    /// - Returns: An array of duplicated elements.
    ///
    func duplicates() -&gt; [Element] {
        var set = Set&lt;Element&gt;()
        var duplicates = Set&lt;Element&gt;()
        forEach {
            if !set.insert($0).inserted {
                duplicates.insert($0)
            }
        }
        return Array(duplicates)
    }
}

// MARK: - Methods (AdditiveArithmetic)

public extension Sequence where Element: AdditiveArithmetic {
    /// SwifterSwift: Sum of all elements in array.
    ///
    ///        [1, 2, 3, 4, 5].sum() -&gt; 15
    ///
    /// - Returns: sum of the array's elements.
    func sum() -&gt; Element {
        return reduce(.zero, +)
    }
}

</code></pre>
<h2 id="for-collection"><a class="header" href="#for-collection">for Collection</a></h2>
<pre><code class="language-swift">
#if canImport(Dispatch)
import Dispatch
#endif

// MARK: - Properties

public extension Collection {
    /// SwifterSwift: The full range of the collection.
    var fullRange: Range&lt;Index&gt; { startIndex..&lt;endIndex }
}

// MARK: - Methods

public extension Collection {
    #if canImport(Dispatch)
    /// SwifterSwift: Performs `each` closure for each element of collection in parallel.
    ///
    ///        array.forEachInParallel { item in
    ///            print(item)
    ///        }
    ///
    /// - Parameter each: closure to run for each element.
    func forEachInParallel(_ each: (Self.Element) -&gt; Void) {
        DispatchQueue.concurrentPerform(iterations: count) {
            each(self[index(startIndex, offsetBy: $0)])
        }
    }
    #endif

    /// SwifterSwift: Safe protects the array from out of bounds by use of optional.
    ///
    ///        let arr = [1, 2, 3, 4, 5]
    ///        arr[safe: 1] -&gt; 2
    ///        arr[safe: 10] -&gt; nil
    ///
    /// - Parameter index: index of element to access element.
    subscript(safe index: Index) -&gt; Element? {
        return indices.contains(index) ? self[index] : nil
    }

    /// SwifterSwift: Returns an array of slices of length &quot;size&quot; from the array. If array can't be split evenly, the final slice will be the remaining elements.
    ///
    ///     [0, 2, 4, 7].group(by: 2) -&gt; [[0, 2], [4, 7]]
    ///     [0, 2, 4, 7, 6].group(by: 2) -&gt; [[0, 2], [4, 7], [6]]
    ///
    /// - Parameter size: The size of the slices to be returned.
    /// - Returns: grouped self.
    func group(by size: Int) -&gt; [[Element]]? {
        // Inspired by: https://lodash.com/docs/4.17.4#chunk
        guard size &gt; 0, !isEmpty else { return nil }
        var start = startIndex
        var slices = [[Element]]()
        while start != endIndex {
            let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex
            slices.append(Array(self[start..&lt;end]))
            start = end
        }
        return slices
    }

    /// SwifterSwift: Get all indices where condition is met.
    ///
    ///     [1, 7, 1, 2, 4, 1, 8].indices(where: { $0 == 1 }) -&gt; [0, 2, 5]
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: all indices where the specified condition evaluates to true (optional).
    func indices(where condition: (Element) throws -&gt; Bool) rethrows -&gt; [Index]? {
        let indices = try self.indices.filter { try condition(self[$0]) }
        return indices.isEmpty ? nil : indices
    }

    /// SwifterSwift: Calls the given closure with an array of size of the parameter slice.
    ///
    ///     [0, 2, 4, 7].forEach(slice: 2) { print($0) } -&gt; // print: [0, 2], [4, 7]
    ///     [0, 2, 4, 7, 6].forEach(slice: 2) { print($0) } -&gt; // print: [0, 2], [4, 7], [6]
    ///
    /// - Parameters:
    ///   - slice: size of array in each interation.
    ///   - body: a closure that takes an array of slice size as a parameter.
    func forEach(slice: Int, body: ([Element]) throws -&gt; Void) rethrows {
        var start = startIndex
        while case let end = index(start, offsetBy: slice, limitedBy: endIndex) ?? endIndex,
            start != end {
            try body(Array(self[start..&lt;end]))
            start = end
        }
    }
    
    /// SwifterSwift: Unique pair of elements in a collection.
    ///
    ///        let array = [1, 2, 3]
    ///        for (first, second) in array.adjacentPairs() {
    ///            print(first, second) // print: (1, 2) (1, 3) (2, 3)
    ///        }
    ///
    ///
    /// - Returns: a sequence of adjacent pairs of elements from this collection.
    func adjacentPairs() -&gt; AnySequence&lt;(Element, Element)&gt; {
        guard var index1 = index(startIndex, offsetBy: 0, limitedBy: endIndex),
              var index2 = index(index1, offsetBy: 1, limitedBy: endIndex) else {
            return AnySequence {
                EmptyCollection.Iterator()
            }
        }
        return AnySequence {
            AnyIterator {
                if index1 &gt;= endIndex || index2 &gt;= endIndex {
                    return nil
                }
                defer {
                    index2 = self.index(after: index2)
                    if index2 &gt;= endIndex {
                        index1 = self.index(after: index1)
                        index2 = self.index(after: index1)
                    }
                }
                return (self[index1], self[index2])
            }
        }
    }
}

// MARK: - Methods (Equatable)

public extension Collection where Element: Equatable {
    /// SwifterSwift: All indices of specified item.
    ///
    ///        [1, 2, 2, 3, 4, 2, 5].indices(of 2) -&gt; [1, 2, 5]
    ///        [1.2, 2.3, 4.5, 3.4, 4.5].indices(of 2.3) -&gt; [1]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].indices(of &quot;l&quot;) -&gt; [2, 3]
    ///
    /// - Parameter item: item to check.
    /// - Returns: an array with all indices of the given item.
    func indices(of item: Element) -&gt; [Index] {
        return indices.filter { self[$0] == item }
    }
}

// MARK: - Methods (BinaryInteger)

public extension Collection where Element: BinaryInteger {
    /// SwifterSwift: Average of all elements in array.
    ///
    /// - Returns: the average of the array's elements.
    func average() -&gt; Double {
        // http://stackoverflow.com/questions/28288148/making-my-function-calculate-average-of-array-swift
        guard !isEmpty else { return .zero }
        return Double(reduce(.zero, +)) / Double(count)
    }
}

// MARK: - Methods (FloatingPoint)

public extension Collection where Element: FloatingPoint {
    /// SwifterSwift: Average of all elements in array.
    ///
    ///        [1.2, 2.3, 4.5, 3.4, 4.5].average() = 3.18
    ///
    /// - Returns: average of the array's elements.
    func average() -&gt; Element {
        guard !isEmpty else { return .zero }
        return reduce(.zero, +) / Element(count)
    }
}
</code></pre>
<h2 id="for-mutablecollection"><a class="header" href="#for-mutablecollection">for MutableCollection</a></h2>
<pre><code class="language-swift">
public extension MutableCollection where Self: RandomAccessCollection {
    /// SwifterSwift: Sort the collection based on a keypath and a compare function.
    ///
    /// - Parameter keyPath: Key path to sort by. The key path type must be Comparable.
    /// - Parameter compare: Comparison function that will determine the ordering.
    mutating func sort&lt;T&gt;(by keyPath: KeyPath&lt;Element, T&gt;, with compare: (T, T) -&gt; Bool) {
        sort { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }

    /// SwifterSwift: Sort the collection based on a keypath.
    ///
    /// - Parameter keyPath: Key path to sort by. The key path type must be Comparable.
    mutating func sort&lt;T: Comparable&gt;(by keyPath: KeyPath&lt;Element, T&gt;) {
        sort { $0[keyPath: keyPath] &lt; $1[keyPath: keyPath] }
    }

    /// SwifterSwift: Sort the collection based on two key paths. The second one will be used in case the values of the first one match.
    ///
    /// - Parameters:
    ///     - keyPath1: Key path to sort by. Must be Comparable.
    ///     - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
    mutating func sort&lt;T: Comparable, U: Comparable&gt;(by keyPath1: KeyPath&lt;Element, T&gt;,
                                                     and keyPath2: KeyPath&lt;Element, U&gt;) {
        sort {
            if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
                return $0[keyPath: keyPath1] &lt; $1[keyPath: keyPath1]
            }
            return $0[keyPath: keyPath2] &lt; $1[keyPath: keyPath2]
        }
    }

    /// SwifterSwift: Sort the collection based on three key paths. Whenever the values of one key path match, the next one will be used.
    ///
    /// - Parameters:
    ///     - keyPath1: Key path to sort by. Must be Comparable.
    ///     - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
    ///     - keyPath3: Key path to sort by in case the values of `keyPath1` and `keyPath2` match. Must be Comparable.
    mutating func sort&lt;T: Comparable, U: Comparable, V: Comparable&gt;(by keyPath1: KeyPath&lt;Element, T&gt;,
                                                                    and keyPath2: KeyPath&lt;Element, U&gt;,
                                                                    and keyPath3: KeyPath&lt;Element, V&gt;) {
        sort {
            if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
                return $0[keyPath: keyPath1] &lt; $1[keyPath: keyPath1]
            }
            if $0[keyPath: keyPath2] != $1[keyPath: keyPath2] {
                return $0[keyPath: keyPath2] &lt; $1[keyPath: keyPath2]
            }
            return $0[keyPath: keyPath3] &lt; $1[keyPath: keyPath3]
        }
    }
}

public extension MutableCollection {
    /// SwifterSwift: Assign a given value to a field `keyPath` of all elements in the collection.
    ///
    /// - Parameters:
    ///   - value: The new value of the field.
    ///   - keyPath: The actual field of the element.
    mutating func assignToAll&lt;Value&gt;(value: Value, by keyPath: WritableKeyPath&lt;Element, Value&gt;) {
        for idx in indices {
            self[idx][keyPath: keyPath] = value
        }
    }
}

</code></pre>
<h2 id="for-rangereplaceablecollection"><a class="header" href="#for-rangereplaceablecollection">for RangeReplaceableCollection</a></h2>
<pre><code class="language-swift">
public extension RangeReplaceableCollection {
    /// SwifterSwift: Creates a new collection of a given size where for each position of the collection the value will be the result of a call of the given expression.
    ///
    ///     let values = Array(expression: &quot;Value&quot;, count: 3)
    ///     print(values)
    ///     // Prints &quot;[&quot;Value&quot;, &quot;Value&quot;, &quot;Value&quot;]&quot;
    ///
    /// - Parameters:
    ///   - expression: The expression to execute for each position of the collection.
    ///   - count: The count of the collection.
    init(expression: @autoclosure () throws -&gt; Element, count: Int) rethrows {
        self.init()
        // swiftlint:disable:next empty_count
        if count &gt; 0 {
            reserveCapacity(count)
            while self.count &lt; count {
                append(try expression())
            }
        }
    }
}

// MARK: - Methods

public extension RangeReplaceableCollection {
    ///  SwifterSwift: Returns a new rotated collection by the given places.
    ///
    ///     [1, 2, 3, 4].rotated(by: 1) -&gt; [4,1,2,3]
    ///     [1, 2, 3, 4].rotated(by: 3) -&gt; [2,3,4,1]
    ///     [1, 2, 3, 4].rotated(by: -1) -&gt; [2,3,4,1]
    ///
    /// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start become the end.
    /// - Returns: The new rotated collection.
    func rotated(by places: Int) -&gt; Self {
        // Inspired by: https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate
        var copy = self
        return copy.rotate(by: places)
    }

    ///  SwifterSwift: Rotate the collection by the given places.
    ///
    ///     [1, 2, 3, 4].rotate(by: 1) -&gt; [4,1,2,3]
    ///     [1, 2, 3, 4].rotate(by: 3) -&gt; [2,3,4,1]
    ///     [1, 2, 3, 4].rotated(by: -1) -&gt; [2,3,4,1]
    ///
    /// - Parameter places: The number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start become the end.
    /// - Returns: self after rotating.
    @discardableResult
    mutating func rotate(by places: Int) -&gt; Self {
        guard places != 0 else { return self }
        let placesToMove = places % count
        if placesToMove &gt; 0 {
            let range = index(endIndex, offsetBy: -placesToMove)...
            let slice = self[range]
            removeSubrange(range)
            insert(contentsOf: slice, at: startIndex)
        } else {
            let range = startIndex..&lt;index(startIndex, offsetBy: -placesToMove)
            let slice = self[range]
            removeSubrange(range)
            append(contentsOf: slice)
        }
        return self
    }

    /// SwifterSwift: Removes the first element of the collection which satisfies the given predicate.
    ///
    ///        [1, 2, 2, 3, 4, 2, 5].removeFirst { $0 % 2 == 0 } -&gt; [1, 2, 3, 4, 2, 5]
    ///        [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;].removeFirst { $0 == &quot;e&quot; } -&gt; [&quot;h&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]
    ///
    /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
    /// - Returns: The first element for which predicate returns true, after removing it. If no elements in the collection satisfy the given predicate, returns `nil`.
    @discardableResult
    mutating func removeFirst(where predicate: (Element) throws -&gt; Bool) rethrows -&gt; Element? {
        guard let index = try firstIndex(where: predicate) else { return nil }
        return remove(at: index)
    }

    /// SwifterSwift: Remove a random value from the collection.
    @discardableResult
    mutating func removeRandomElement() -&gt; Element? {
        guard let randomIndex = indices.randomElement() else { return nil }
        return remove(at: randomIndex)
    }

    /// SwifterSwift: Keep elements of Array while condition is true.
    ///
    ///        [0, 2, 4, 7].keep(while: { $0 % 2 == 0 }) -&gt; [0, 2, 4]
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: self after applying provided condition.
    /// - Throws: provided condition exception.
    @discardableResult
    mutating func keep(while condition: (Element) throws -&gt; Bool) rethrows -&gt; Self {
        if let idx = try firstIndex(where: { try !condition($0) }) {
            removeSubrange(idx...)
        }
        return self
    }

    /// SwifterSwift: Take element of Array while condition is true.
    ///
    ///        [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -&gt; [0, 2, 4]
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: All elements up until condition evaluates to false.
    func take(while condition: (Element) throws -&gt; Bool) rethrows -&gt; Self {
        return Self(try prefix(while: condition))
    }

    /// SwifterSwift: Skip elements of Array while condition is true.
    ///
    ///        [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -&gt; [6, 8]
    ///
    /// - Parameter condition: condition to evaluate each element against.
    /// - Returns: All elements after the condition evaluates to false.
    func skip(while condition: (Element) throws -&gt; Bool) rethrows -&gt; Self {
        guard let idx = try firstIndex(where: { try !condition($0) }) else { return Self() }
        return Self(self[idx...])
    }

    /// SwifterSwift: Remove all duplicate elements using KeyPath to compare.
    ///
    /// - Parameter path: Key path to compare, the value must be Equatable.
    mutating func removeDuplicates&lt;E: Equatable&gt;(keyPath path: KeyPath&lt;Element, E&gt;) {
        var items = [Element]()
        removeAll { element -&gt; Bool in
            guard items.contains(where: { $0[keyPath: path] == element[keyPath: path] }) else {
                items.append(element)
                return false
            }
            return true
        }
    }

    /// SwifterSwift: Remove all duplicate elements using KeyPath to compare.
    ///
    /// - Parameter path: Key path to compare, the value must be Hashable.
    mutating func removeDuplicates&lt;E: Hashable&gt;(keyPath path: KeyPath&lt;Element, E&gt;) {
        var set = Set&lt;E&gt;()
        removeAll { !set.insert($0[keyPath: path]).inserted }
    }

    /// SwifterSwift: Accesses the element at the specified position.
    ///
    /// - Parameter offset: The offset position of the element to access. `offset` must be a valid index offset of the collection that is not equal to the `endIndex` property.
    subscript(offset: Int) -&gt; Element {
        get {
            return self[index(startIndex, offsetBy: offset)]
        }
        set {
            let offsetIndex = index(startIndex, offsetBy: offset)
            replaceSubrange(offsetIndex..&lt;index(after: offsetIndex), with: [newValue])
        }
    }

    /// SwifterSwift: Accesses a contiguous subrange of the collection’s elements.
    ///
    /// - Parameter range: A range of the collection’s indices offsets. The bounds of the range must be valid indices of the collection.
    subscript&lt;R&gt;(range: R) -&gt; SubSequence where R: RangeExpression, R.Bound == Int {
        get {
            let indexRange = range.relative(to: 0..&lt;count)
            return self[index(startIndex, offsetBy: indexRange.lowerBound)..&lt;index(startIndex,
                                                                                   offsetBy: indexRange.upperBound)]
        }
        set {
            let indexRange = range.relative(to: 0..&lt;count)
            replaceSubrange(
                index(startIndex, offsetBy: indexRange.lowerBound)..&lt;index(startIndex, offsetBy: indexRange.upperBound),
                with: newValue)
        }
    }
    
    /**
     SwifterSwift: Adds a new element at the end of the array, mutates the array in place
     - Parameter newElement: The optional element to append to the array
     */
    mutating func appendIfNonNil(_ newElement: Element?) {
        guard let newElement = newElement else { return }
        self.append(newElement)
    }
    
    /**
     SwifterSwift: Adds the elements of a sequence to the end of the array, mutates the array in place
     - Parameter newElements: The optional sequence to append to the array
     */
    mutating func appendIfNonNil&lt;S&gt;(contentsOf newElements: S?) where Element == S.Element, S : Sequence {
        guard let newElements = newElements else { return }
        self.append(contentsOf: newElements)
    }
}
</code></pre>
<h2 id="for-bidirectionalcollection"><a class="header" href="#for-bidirectionalcollection">for BidirectionalCollection</a></h2>
<pre><code class="language-swift">public extension BidirectionalCollection {
    /// SwifterSwift: Returns the element at the specified position. If offset is negative, the `n`th element from the end will be returned where `n` is the result of `abs(distance)`.
    ///
    ///        let arr = [1, 2, 3, 4, 5]
    ///        arr[offset: 1] -&gt; 2
    ///        arr[offset: -2] -&gt; 4
    ///
    /// - Parameter distance: The distance to offset.
    subscript(offset distance: Int) -&gt; Element {
        let index = distance &gt;= 0 ? startIndex : endIndex
        return self[indices.index(index, offsetBy: distance)]
    }

    /// SwifterSwift: Returns the last element of the sequence with having property by given key path equals to given `value`.
    ///
    /// - Parameters:
    ///   - keyPath: The `KeyPath` of property for `Element` to compare.
    ///   - value: The value to compare with `Element` property
    /// - Returns: The last element of the collection that has property by given key path equals to given `value` or `nil` if there is no such element.
    func last&lt;T: Equatable&gt;(where keyPath: KeyPath&lt;Element, T&gt;, equals value: T) -&gt; Element? {
        return last { $0[keyPath: keyPath] == value }
    }
}

</code></pre>
<h2 id="for-binaryfloatingpoint"><a class="header" href="#for-binaryfloatingpoint">for BinaryFloatingPoint</a></h2>
<pre><code class="language-swift">#if canImport(Foundation)
import Foundation

// MARK: - Methods

public extension BinaryFloatingPoint {
    #if canImport(Foundation)
    /// SwifterSwift: Returns a rounded value with the specified number of decimal places and rounding rule. If `numberOfDecimalPlaces` is negative, `0` will be used.
    ///
    ///     let num = 3.1415927
    ///     num.rounded(numberOfDecimalPlaces: 3, rule: .up) -&gt; 3.142
    ///     num.rounded(numberOfDecimalPlaces: 3, rule: .down) -&gt; 3.141
    ///     num.rounded(numberOfDecimalPlaces: 2, rule: .awayFromZero) -&gt; 3.15
    ///     num.rounded(numberOfDecimalPlaces: 4, rule: .towardZero) -&gt; 3.1415
    ///     num.rounded(numberOfDecimalPlaces: -1, rule: .toNearestOrEven) -&gt; 3
    ///
    /// - Parameters:
    ///   - numberOfDecimalPlaces: The expected number of decimal places.
    ///   - rule: The rounding rule to use.
    /// - Returns: The rounded value.
    func rounded(numberOfDecimalPlaces: Int, rule: FloatingPointRoundingRule) -&gt; Self {
        let factor = Self(pow(10.0, Double(max(0, numberOfDecimalPlaces))))
        return (self * factor).rounded(rule) / factor
    }
    #endif
}

#endif
</code></pre>
<h2 id="for-binaryinteger"><a class="header" href="#for-binaryinteger">for BinaryInteger</a></h2>
<pre><code class="language-swift">// MARK: - Properties

public extension BinaryInteger {
    /// SwifterSwift: The raw bytes of the integer.
    ///
    ///     var number = Int16(-128)
    ///     print(number.bytes)
    ///     // prints &quot;[255, 128]&quot;
    ///
    var bytes: [UInt8] {
        var result = [UInt8]()
        result.reserveCapacity(MemoryLayout&lt;Self&gt;.size)
        var value = self
        for _ in 0..&lt;MemoryLayout&lt;Self&gt;.size {
            result.append(UInt8(truncatingIfNeeded: value))
            value &gt;&gt;= 8
        }
        return result.reversed()
    }
}

// MARK: - Initializers

public extension BinaryInteger {
    /// SwifterSwift: Creates a `BinaryInteger` from a raw byte representation.
    ///
    ///     var number = Int16(bytes: [0xFF, 0b1111_1101])
    ///     print(number!)
    ///     // prints &quot;-3&quot;
    ///
    /// - Parameter bytes: An array of bytes representing the value of the integer.
    init?(bytes: [UInt8]) {
        // https://stackoverflow.com/a/43518567/9506784
        precondition(bytes.count &lt;= MemoryLayout&lt;Self&gt;.size,
                     &quot;Integer with a \(bytes.count) byte binary representation of '\(bytes.map({ String($0, radix: 2) }).joined(separator: &quot; &quot;))' overflows when stored into a \(MemoryLayout&lt;Self&gt;.size) byte '\(Self.self)'&quot;)
        var value: Self = 0
        for byte in bytes {
            value &lt;&lt;= 8
            value |= Self(byte)
        }
        self.init(exactly: value)
    }
}

</code></pre>
<h2 id="for-bool"><a class="header" href="#for-bool">for Bool</a></h2>
<pre><code class="language-swift">// MARK: - Properties

public extension Bool {
    /// SwifterSwift: Return 1 if true, or 0 if false.
    ///
    ///        false.int -&gt; 0
    ///        true.int -&gt; 1
    ///
    var int: Int {
        return self ? 1 : 0
    }

    /// SwifterSwift: Return &quot;true&quot; if true, or &quot;false&quot; if false.
    ///
    ///        false.string -&gt; &quot;false&quot;
    ///        true.string -&gt; &quot;true&quot;
    ///
    var string: String {
        return self ? &quot;true&quot; : &quot;false&quot;
    }
}
</code></pre>
<h2 id="for-character"><a class="header" href="#for-character">for Character</a></h2>
<pre><code class="language-swift">
public extension Character {
    /// SwifterSwift: Check if character is emoji.
    ///
    ///        Character(&quot;😀&quot;).isEmoji -&gt; true
    ///
    var isEmoji: Bool {
        // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
        let scalarValue = String(self).unicodeScalars.first!.value
        switch scalarValue {
        case 0x1F600...0x1F64F, // Emoticons
             0x1F300...0x1F5FF, // Misc Symbols and Pictographs
             0x1F680...0x1F6FF, // Transport and Map
             0x1F1E6...0x1F1FF, // Regional country flags
             0x2600...0x26FF, // Misc symbols
             0x2700...0x27BF, // Dingbats
             0xE0020...0xE007F, // Tags
             0xFE00...0xFE0F, // Variation Selectors
             0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
             127_000...127_600, // Various asian characters
             65024...65039, // Variation selector
             9100...9300, // Misc items
             8400...8447: // Combining Diacritical Marks for Symbols
            return true
        default:
            return false
        }
    }

    /// SwifterSwift: Integer from character (if applicable).
    ///
    ///        Character(&quot;1&quot;).int -&gt; 1
    ///        Character(&quot;A&quot;).int -&gt; nil
    ///
    var int: Int? {
        return Int(String(self))
    }

    /// SwifterSwift: String from character.
    ///
    ///        Character(&quot;a&quot;).string -&gt; &quot;a&quot;
    ///
    var string: String {
        return String(self)
    }

    /// SwifterSwift: Return the character lowercased.
    ///
    ///        Character(&quot;A&quot;).lowercased -&gt; Character(&quot;a&quot;)
    ///
    var lowercased: Character {
        return String(self).lowercased().first!
    }

    /// SwifterSwift: Return the character uppercased.
    ///
    ///        Character(&quot;a&quot;).uppercased -&gt; Character(&quot;A&quot;)
    ///
    var uppercased: Character {
        return String(self).uppercased().first!
    }
}

// MARK: - Methods

public extension Character {
    /// SwifterSwift: Random character.
    ///
    ///    Character.random() -&gt; k
    ///
    /// - Returns: A random character.
    static func randomAlphanumeric() -&gt; Character {
        return &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;.randomElement()!
    }
}

// MARK: - Operators

public extension Character {
    /// SwifterSwift: Repeat character multiple times.
    ///
    ///        Character(&quot;-&quot;) * 10 -&gt; &quot;----------&quot;
    ///
    /// - Parameters:
    ///   - lhs: character to repeat.
    ///   - rhs: number of times to repeat character.
    /// - Returns: string with character repeated n times.
    static func * (lhs: Character, rhs: Int) -&gt; String {
        guard rhs &gt; 0 else { return &quot;&quot; }
        return String(repeating: String(lhs), count: rhs)
    }

    /// SwifterSwift: Repeat character multiple times.
    ///
    ///        10 * Character(&quot;-&quot;) -&gt; &quot;----------&quot;
    ///
    /// - Parameters:
    ///   - lhs: number of times to repeat character.
    ///   - rhs: character to repeat.
    /// - Returns: string with character repeated n times.
    static func * (lhs: Int, rhs: Character) -&gt; String {
        guard lhs &gt; 0 else { return &quot;&quot; }
        return String(repeating: String(rhs), count: lhs)
    }
}
</code></pre>
<h2 id="for-comparable"><a class="header" href="#for-comparable">for Comparable</a></h2>
<pre><code class="language-swift">
public extension Comparable {
    /// SwifterSwift: Returns true if value is in the provided range.
    ///
    ///    1.isBetween(5...7) // false
    ///    7.isBetween(6...12) // true
    ///    date.isBetween(date1...date2)
    ///    &quot;c&quot;.isBetween(a...d) // true
    ///    0.32.isBetween(0.31...0.33) // true
    ///
    /// - Parameter range: Closed range against which the value is checked to be included.
    /// - Returns: `true` if the value is included in the range, `false` otherwise.
    func isBetween(_ range: ClosedRange&lt;Self&gt;) -&gt; Bool {
        return range ~= self
    }

    /// SwifterSwift: Returns value limited within the provided range.
    ///
    ///     1.clamped(to: 3...8) // 3
    ///     4.clamped(to: 3...7) // 4
    ///     &quot;c&quot;.clamped(to: &quot;e&quot;...&quot;g&quot;) // &quot;e&quot;
    ///     0.32.clamped(to: 0.1...0.29) // 0.29
    ///
    /// - Parameter range: Closed range that limits the value.
    /// - Returns: A value limited to the range, i.e. between `range.lowerBound` and `range.upperBound`.
    func clamped(to range: ClosedRange&lt;Self&gt;) -&gt; Self {
        return max(range.lowerBound, min(self, range.upperBound))
    }
}
</code></pre>
<h2 id="for-decodable"><a class="header" href="#for-decodable">for Decodable</a></h2>
<pre><code class="language-swift">#if canImport(Foundation)
import Foundation
#endif

public extension Decodable {
    #if canImport(Foundation)
    /// SwifterSwift: Parsing the model in Decodable type.
    /// - Parameters:
    ///   - data: Data.
    ///   - decoder: JSONDecoder. Initialized by default.
    init?(from data: Data, using decoder: JSONDecoder = .init()) {
        guard let parsed = try? decoder.decode(Self.self, from: data) else { return nil }
        self = parsed
    }
    #endif
}
</code></pre>
<h2 id="for-dictionary"><a class="header" href="#for-dictionary">for Dictionary</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation
#endif

// MARK: - Methods

public extension Dictionary {
    /// SwifterSwift: Creates a Dictionary from a given sequence grouped by a given key path.
    ///
    /// - Parameters:
    ///   - sequence: Sequence being grouped.
    ///   - keypath: The key path to group by.
    init&lt;S: Sequence&gt;(grouping sequence: S, by keyPath: KeyPath&lt;S.Element, Key&gt;) where Value == [S.Element] {
        self.init(grouping: sequence, by: { $0[keyPath: keyPath] })
    }

    /// SwifterSwift: Check if key exists in dictionary.
    ///
    ///        let dict: [String: Any] = [&quot;testKey&quot;: &quot;testValue&quot;, &quot;testArrayKey&quot;: [1, 2, 3, 4, 5]]
    ///        dict.has(key: &quot;testKey&quot;) -&gt; true
    ///        dict.has(key: &quot;anotherKey&quot;) -&gt; false
    ///
    /// - Parameter key: key to search for.
    /// - Returns: true if key exists in dictionary.
    func has(key: Key) -&gt; Bool {
        return index(forKey: key) != nil
    }

    /// SwifterSwift: Remove all keys contained in the keys parameter from the dictionary.
    ///
    ///        var dict : [String: String] = [&quot;key1&quot; : &quot;value1&quot;, &quot;key2&quot; : &quot;value2&quot;, &quot;key3&quot; : &quot;value3&quot;]
    ///        dict.removeAll(keys: [&quot;key1&quot;, &quot;key2&quot;])
    ///        dict.keys.contains(&quot;key3&quot;) -&gt; true
    ///        dict.keys.contains(&quot;key1&quot;) -&gt; false
    ///        dict.keys.contains(&quot;key2&quot;) -&gt; false
    ///
    /// - Parameter keys: keys to be removed.
    mutating func removeAll&lt;S: Sequence&gt;(keys: S) where S.Element == Key {
        keys.forEach { removeValue(forKey: $0) }
    }

    /// SwifterSwift: Remove a value for a random key from the dictionary.
    @discardableResult
    mutating func removeValueForRandomKey() -&gt; Value? {
        guard let randomKey = keys.randomElement() else { return nil }
        return removeValue(forKey: randomKey)
    }

    #if canImport(Foundation)
    /// SwifterSwift: JSON Data from dictionary.
    ///
    /// - Parameter prettify: set true to prettify data (default is false).
    /// - Returns: optional JSON Data (if applicable).
    func jsonData(prettify: Bool = false) -&gt; Data? {
        guard JSONSerialization.isValidJSONObject(self) else {
            return nil
        }
        let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization
            .WritingOptions()
        return try? JSONSerialization.data(withJSONObject: self, options: options)
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: JSON String from dictionary.
    ///
    ///        dict.jsonString() -&gt; &quot;{&quot;testKey&quot;:&quot;testValue&quot;,&quot;testArrayKey&quot;:[1,2,3,4,5]}&quot;
    ///
    ///        dict.jsonString(prettify: true)
    ///        /*
    ///        returns the following string:
    ///
    ///        &quot;{
    ///        &quot;testKey&quot; : &quot;testValue&quot;,
    ///        &quot;testArrayKey&quot; : [
    ///            1,
    ///            2,
    ///            3,
    ///            4,
    ///            5
    ///        ]
    ///        }&quot;
    ///
    ///        */
    ///
    /// - Parameter prettify: set true to prettify string (default is false).
    /// - Returns: optional JSON String (if applicable).
    func jsonString(prettify: Bool = false) -&gt; String? {
        guard JSONSerialization.isValidJSONObject(self) else { return nil }
        let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization
            .WritingOptions()
        guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) else { return nil }
        return String(data: jsonData, encoding: .utf8)
    }
    #endif

    /// SwifterSwift: Returns a dictionary containing the results of mapping the given closure over the sequence’s elements.
    /// - Parameter transform: A mapping closure. `transform` accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.
    /// - Returns: A dictionary containing the transformed elements of this sequence.
    func mapKeysAndValues&lt;K, V&gt;(_ transform: ((key: Key, value: Value)) throws -&gt; (K, V)) rethrows -&gt; [K: V] {
        return [K: V](uniqueKeysWithValues: try map(transform))
    }

    /// SwifterSwift: Returns a dictionary containing the non-`nil` results of calling the given transformation with each element of this sequence.
    /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
    /// - Returns: A dictionary of the non-`nil` results of calling `transform` with each element of the sequence.
    /// - Complexity: *O(m + n)*, where _m_ is the length of this sequence and _n_ is the length of the result.
    func compactMapKeysAndValues&lt;K, V&gt;(_ transform: ((key: Key, value: Value)) throws -&gt; (K, V)?) rethrows -&gt; [K: V] {
        return [K: V](uniqueKeysWithValues: try compactMap(transform))
    }

    /// SwifterSwift: Creates a new dictionary using specified keys.
    ///
    ///        var dict =  [&quot;key1&quot;: 1, &quot;key2&quot;: 2, &quot;key3&quot;: 3, &quot;key4&quot;: 4]
    ///        dict.pick(keys: [&quot;key1&quot;, &quot;key3&quot;, &quot;key4&quot;]) -&gt; [&quot;key1&quot;: 1, &quot;key3&quot;: 3, &quot;key4&quot;: 4]
    ///        dict.pick(keys: [&quot;key2&quot;]) -&gt; [&quot;key2&quot;: 2]
    ///
    /// - Complexity: O(K), where _K_ is the length of the keys array.
    ///
    /// - Parameter keys: An array of keys that will be the entries in the resulting dictionary.
    ///
    /// - Returns: A new dictionary that contains the specified keys only. If none of the keys exist, an empty dictionary will be returned.
    func pick(keys: [Key]) -&gt; [Key: Value] {
        keys.reduce(into: [Key: Value]()) { result, item in
            result[item] = self[item]
        }
    }
}

// MARK: - Methods (Value: Equatable)

public extension Dictionary where Value: Equatable {
    /// SwifterSwift: Returns an array of all keys that have the given value in dictionary.
    ///
    ///        let dict = [&quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value1&quot;, &quot;key3&quot;: &quot;value2&quot;]
    ///        dict.keys(forValue: &quot;value1&quot;) -&gt; [&quot;key1&quot;, &quot;key2&quot;]
    ///        dict.keys(forValue: &quot;value2&quot;) -&gt; [&quot;key3&quot;]
    ///        dict.keys(forValue: &quot;value3&quot;) -&gt; []
    ///
    /// - Parameter value: Value for which keys are to be fetched.
    /// - Returns: An array containing keys that have the given value.
    func keys(forValue value: Value) -&gt; [Key] {
        return keys.filter { self[$0] == value }
    }
}

// MARK: - Methods (ExpressibleByStringLiteral)

public extension Dictionary where Key: StringProtocol {
    /// SwifterSwift: Lowercase all keys in dictionary.
    ///
    ///        var dict = [&quot;tEstKeY&quot;: &quot;value&quot;]
    ///        dict.lowercaseAllKeys()
    ///        print(dict) // prints &quot;[&quot;testkey&quot;: &quot;value&quot;]&quot;
    ///
    mutating func lowercaseAllKeys() {
        // http://stackoverflow.com/questions/33180028/extend-dictionary-where-key-is-of-type-string
        for key in keys {
            if let lowercaseKey = String(describing: key).lowercased() as? Key {
                self[lowercaseKey] = removeValue(forKey: key)
            }
        }
    }
}

// MARK: - Subscripts

public extension Dictionary {
    /// SwifterSwift: Deep fetch or set a value from nested dictionaries.
    ///
    ///        var dict =  [&quot;key&quot;: [&quot;key1&quot;: [&quot;key2&quot;: &quot;value&quot;]]]
    ///        dict[path: [&quot;key&quot;, &quot;key1&quot;, &quot;key2&quot;]] = &quot;newValue&quot;
    ///        dict[path: [&quot;key&quot;, &quot;key1&quot;, &quot;key2&quot;]] -&gt; &quot;newValue&quot;
    ///
    /// - Note: Value fetching is iterative, while setting is recursive.
    ///
    /// - Complexity: O(N), _N_ being the length of the path passed in.
    ///
    /// - Parameter path: An array of keys to the desired value.
    ///
    /// - Returns: The value for the key-path passed in. `nil` if no value is found.
    subscript(path path: [Key]) -&gt; Any? {
        get {
            guard !path.isEmpty else { return nil }
            var result: Any? = self
            for key in path {
                if let element = (result as? [Key: Any])?[key] {
                    result = element
                } else {
                    return nil
                }
            }
            return result
        }
        set {
            if let first = path.first {
                if path.count == 1, let new = newValue as? Value {
                    return self[first] = new
                }
                if var nested = self[first] as? [Key: Any] {
                    nested[path: Array(path.dropFirst())] = newValue
                    return self[first] = nested as? Value
                }
            }
        }
    }
}

// MARK: - Operators

public extension Dictionary {
    /// SwifterSwift: Merge the keys/values of two dictionaries.
    ///
    ///        let dict: [String: String] = [&quot;key1&quot;: &quot;value1&quot;]
    ///        let dict2: [String: String] = [&quot;key2&quot;: &quot;value2&quot;]
    ///        let result = dict + dict2
    ///        result[&quot;key1&quot;] -&gt; &quot;value1&quot;
    ///        result[&quot;key2&quot;] -&gt; &quot;value2&quot;
    ///
    /// - Parameters:
    ///   - lhs: dictionary.
    ///   - rhs: dictionary.
    /// - Returns: An dictionary with keys and values from both.
    static func + (lhs: [Key: Value], rhs: [Key: Value]) -&gt; [Key: Value] {
        var result = lhs
        rhs.forEach { result[$0] = $1 }
        return result
    }

    // MARK: - Operators

    /// SwifterSwift: Append the keys and values from the second dictionary into the first one.
    ///
    ///        var dict: [String: String] = [&quot;key1&quot;: &quot;value1&quot;]
    ///        let dict2: [String: String] = [&quot;key2&quot;: &quot;value2&quot;]
    ///        dict += dict2
    ///        dict[&quot;key1&quot;] -&gt; &quot;value1&quot;
    ///        dict[&quot;key2&quot;] -&gt; &quot;value2&quot;
    ///
    /// - Parameters:
    ///   - lhs: dictionary.
    ///   - rhs: dictionary.
    static func += (lhs: inout [Key: Value], rhs: [Key: Value]) {
        rhs.forEach { lhs[$0] = $1 }
    }

    /// SwifterSwift: Remove keys contained in the sequence from the dictionary.
    ///
    ///        let dict: [String: String] = [&quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot;, &quot;key3&quot;: &quot;value3&quot;]
    ///        let result = dict-[&quot;key1&quot;, &quot;key2&quot;]
    ///        result.keys.contains(&quot;key3&quot;) -&gt; true
    ///        result.keys.contains(&quot;key1&quot;) -&gt; false
    ///        result.keys.contains(&quot;key2&quot;) -&gt; false
    ///
    /// - Parameters:
    ///   - lhs: dictionary.
    ///   - keys: array with the keys to be removed.
    /// - Returns: a new dictionary with keys removed.
    static func - &lt;S: Sequence&gt;(lhs: [Key: Value], keys: S) -&gt; [Key: Value] where S.Element == Key {
        var result = lhs
        result.removeAll(keys: keys)
        return result
    }

    /// SwifterSwift: Remove keys contained in the sequence from the dictionary.
    ///
    ///        var dict: [String: String] = [&quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot;, &quot;key3&quot;: &quot;value3&quot;]
    ///        dict-=[&quot;key1&quot;, &quot;key2&quot;]
    ///        dict.keys.contains(&quot;key3&quot;) -&gt; true
    ///        dict.keys.contains(&quot;key1&quot;) -&gt; false
    ///        dict.keys.contains(&quot;key2&quot;) -&gt; false
    ///
    /// - Parameters:
    ///   - lhs: dictionary.
    ///   - keys: array with the keys to be removed.
    static func -= &lt;S: Sequence&gt;(lhs: inout [Key: Value], keys: S) where S.Element == Key {
        lhs.removeAll(keys: keys)
    }
}
</code></pre>
<h2 id="for-double"><a class="header" href="#for-double">for Double</a></h2>
<pre><code class="language-swift">
#if canImport(CoreGraphics)
import CoreGraphics
#endif

#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

// MARK: - Properties

public extension Double {
    /// SwifterSwift: Int.
    var int: Int {
        return Int(self)
    }

    /// SwifterSwift: Float.
    var float: Float {
        return Float(self)
    }

    #if canImport(CoreGraphics)
    /// SwifterSwift: CGFloat.
    var cgFloat: CGFloat {
        return CGFloat(self)
    }
    #endif
}

// MARK: - Operators

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator **: PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
///   - lhs: base double.
///   - rhs: exponent double.
/// - Returns: exponentiation result (example: 4.4 ** 0.5 = 2.0976176963).
public func ** (lhs: Double, rhs: Double) -&gt; Double {
    // http://nshipster.com/swift-operators/
    return pow(lhs, rhs)
}

</code></pre>
<h2 id="for-float"><a class="header" href="#for-float">for Float</a></h2>
<pre><code class="language-swift">
#if canImport(CoreGraphics)
import CoreGraphics
#endif

#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

// MARK: - Properties

public extension Float {
    /// SwifterSwift: Int.
    var int: Int {
        return Int(self)
    }

    /// SwifterSwift: Double.
    var double: Double {
        return Double(self)
    }

    #if canImport(CoreGraphics)
    /// SwifterSwift: CGFloat.
    var cgFloat: CGFloat {
        return CGFloat(self)
    }
    #endif
}

// MARK: - Operators

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator **: PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
///   - lhs: base float.
///   - rhs: exponent float.
/// - Returns: exponentiation result (4.4 ** 0.5 = 2.0976176963).
public func ** (lhs: Float, rhs: Float) -&gt; Float {
    // http://nshipster.com/swift-operators/
    return pow(lhs, rhs)
}

</code></pre>
<h2 id="for-floatingpoint"><a class="header" href="#for-floatingpoint">for FloatingPoint</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation
#endif

// MARK: - Properties

public extension FloatingPoint {
    /// SwifterSwift: Absolute value of number.
    var abs: Self {
        return Swift.abs(self)
    }

    /// SwifterSwift: Check if number is positive.
    var isPositive: Bool {
        return self &gt; 0
    }

    /// SwifterSwift: Check if number is negative.
    var isNegative: Bool {
        return self &lt; 0
    }

    #if canImport(Foundation)
    /// SwifterSwift: Ceil of number.
    var ceil: Self {
        return Foundation.ceil(self)
    }
    #endif

    /// SwifterSwift: Radian value of degree input.
    var degreesToRadians: Self {
        return Self.pi * self / Self(180)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Floor of number.
    var floor: Self {
        return Foundation.floor(self)
    }
    #endif

    /// SwifterSwift: Degree value of radian input.
    var radiansToDegrees: Self {
        return self * Self(180) / Self.pi
    }
}

// MARK: - Operators

// swiftlint:disable identifier_name
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
///   - lhs: number.
///   - rhs: number.
/// - Returns: tuple of plus-minus operation ( 2.5 ± 1.5 -&gt; (4, 1)).
public func ± &lt;T: FloatingPoint&gt;(lhs: T, rhs: T) -&gt; (T, T) {
    // http://nshipster.com/swift-operators/
    return (lhs + rhs, lhs - rhs)
}

// swiftlint:enable identifier_name

// swiftlint:disable identifier_name
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: number.
/// - Returns: tuple of plus-minus operation (± 2.5 -&gt; (2.5, -2.5)).
public prefix func ± &lt;T: FloatingPoint&gt;(number: T) -&gt; (T, T) {
    // http://nshipster.com/swift-operators/
    return 0 ± number
}

// swiftlint:enable identifier_name

// swiftlint:disable identifier_name
prefix operator √
/// SwifterSwift: Square root of float.
///
/// - Parameter float: float value to find square root for.
/// - Returns: square root of given float.
public prefix func √ &lt;T&gt;(float: T) -&gt; T where T: FloatingPoint {
    // http://nshipster.com/swift-operators/
    return sqrt(float)
}

// swiftlint:enable identifier_name
</code></pre>
<h2 id="for-int"><a class="header" href="#for-int">for Int</a></h2>
<pre><code class="language-swift">
#if canImport(CoreGraphics)
import CoreGraphics
#endif

#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

// MARK: - Properties

public extension Int {
    /// SwifterSwift: CountableRange 0..&lt;Int.
    var countableRange: CountableRange&lt;Int&gt; {
        return 0..&lt;self
    }

    /// SwifterSwift: Radian value of degree input.
    var degreesToRadians: Double {
        return Double.pi * Double(self) / 180.0
    }

    /// SwifterSwift: Degree value of radian input.
    var radiansToDegrees: Double {
        return Double(self) * 180 / Double.pi
    }

    /// SwifterSwift: UInt.
    var uInt: UInt {
        return UInt(self)
    }

    /// SwifterSwift: Double.
    var double: Double {
        return Double(self)
    }

    /// SwifterSwift: Float.
    var float: Float {
        return Float(self)
    }

    #if canImport(CoreGraphics)
    /// SwifterSwift: CGFloat.
    var cgFloat: CGFloat {
        return CGFloat(self)
    }
    #endif

    /// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..).
    var kFormatted: String {
        var sign: String {
            return self &gt;= 0 ? &quot;&quot; : &quot;-&quot;
        }
        let abs = Swift.abs(self)
        if abs == 0 {
            return &quot;0k&quot;
        } else if abs &gt;= 0, abs &lt; 1000 {
            return &quot;0k&quot;
        } else if abs &gt;= 1000, abs &lt; 1_000_000 {
            return String(format: &quot;\(sign)%ik&quot;, abs / 1000)
        }
        return String(format: &quot;\(sign)%ikk&quot;, abs / 100_000)
    }

    /// SwifterSwift: Array of digits of integer value.
    var digits: [Int] {
        guard self != 0 else { return [0] }
        var digits = [Int]()
        var number = abs

        while number != 0 {
            let xNumber = number % 10
            digits.append(xNumber)
            number /= 10
        }

        digits.reverse()
        return digits
    }

    /// SwifterSwift: Number of digits of integer value.
    var digitsCount: Int {
        guard self != 0 else { return 1 }
        let number = Double(abs)
        return Int(log10(number) + 1)
    }
}

// MARK: - Methods

public extension Int {
    /// SwifterSwift: check if given integer prime or not. Warning: Using big numbers can be computationally expensive!
    /// - Returns: true or false depending on prime-ness.
    func isPrime() -&gt; Bool {
        // To improve speed on latter loop :)
        if self == 2 { return true }

        guard self &gt; 1, self % 2 != 0 else { return false }

        // Explanation: It is enough to check numbers until
        // the square root of that number. If you go up from N by one,
        // other multiplier will go 1 down to get similar result
        // (integer-wise operation) such way increases speed of operation
        let base = Int(sqrt(Double(self)))
        for int in Swift.stride(from: 3, through: base, by: 2) where self % int == 0 {
            return false
        }
        return true
    }

    /// SwifterSwift: Roman numeral string from integer (if applicable).
    ///
    ///     10.romanNumeral() -&gt; &quot;X&quot;
    ///
    /// - Returns: The roman numeral string.
    func romanNumeral() -&gt; String? {
        // https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7
        guard self &gt; 0 else { // there is no roman numeral for 0 or negative numbers
            return nil
        }
        let romanValues = [&quot;M&quot;, &quot;CM&quot;, &quot;D&quot;, &quot;CD&quot;, &quot;C&quot;, &quot;XC&quot;, &quot;L&quot;, &quot;XL&quot;, &quot;X&quot;, &quot;IX&quot;, &quot;V&quot;, &quot;IV&quot;, &quot;I&quot;]
        let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

        var romanValue = &quot;&quot;
        var startingValue = self

        for (index, romanChar) in romanValues.enumerated() {
            let arabicValue = arabicValues[index]
            let div = startingValue / arabicValue
            for _ in 0..&lt;div {
                romanValue.append(romanChar)
            }
            startingValue -= arabicValue * div
        }
        return romanValue
    }

    /// SwifterSwift: Rounds to the closest multiple of n.
    func roundToNearest(_ number: Int) -&gt; Int {
        return number == 0 ? self : Int(round(Double(self) / Double(number))) * number
    }
}

// MARK: - Operators

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator **: PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
///   - lhs: base integer.
///   - rhs: exponent integer.
/// - Returns: exponentiation result (example: 2 ** 3 = 8).
public func ** (lhs: Int, rhs: Int) -&gt; Double {
    // http://nshipster.com/swift-operators/
    return pow(Double(lhs), Double(rhs))
}

// swiftlint:disable identifier_name
prefix operator √
/// SwifterSwift: Square root of integer.
///
/// - Parameter int: integer value to find square root for.
/// - Returns: square root of given integer.
public prefix func √ (int: Int) -&gt; Double {
    // http://nshipster.com/swift-operators/
    return sqrt(Double(int))
}

// swiftlint:enable identifier_name

// swiftlint:disable identifier_name
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
///   - lhs: integer number.
///   - rhs: integer number.
/// - Returns: tuple of plus-minus operation (example: 2 ± 3 -&gt; (5, -1)).
public func ± (lhs: Int, rhs: Int) -&gt; (Int, Int) {
    // http://nshipster.com/swift-operators/
    return (lhs + rhs, lhs - rhs)
}

// swiftlint:enable identifier_name

// swiftlint:disable identifier_name
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: integer number.
/// - Returns: tuple of plus-minus operation (example: ± 2 -&gt; (2, -2)).
public prefix func ± (int: Int) -&gt; (Int, Int) {
    // http://nshipster.com/swift-operators/
    return (int, -int)
}

// swiftlint:enable identifier_name

</code></pre>
<h2 id="for-signedinteger"><a class="header" href="#for-signedinteger">for SignedInteger</a></h2>
<pre><code class="language-swift">#if canImport(Foundation)
import Foundation
#endif

// MARK: - Properties

public extension SignedInteger {
    /// SwifterSwift: Absolute value of integer number.
    var abs: Self {
        return Swift.abs(self)
    }

    /// SwifterSwift: Check if integer is positive.
    var isPositive: Bool {
        return self &gt; 0
    }

    /// SwifterSwift: Check if integer is negative.
    var isNegative: Bool {
        return self &lt; 0
    }

    /// SwifterSwift: Check if integer is even.
    var isEven: Bool {
        return (self % 2) == 0
    }

    /// SwifterSwift: Check if integer is odd.
    var isOdd: Bool {
        return (self % 2) != 0
    }

    /// SwifterSwift: String of format (XXh XXm) from seconds Int.
    var timeString: String {
        guard self &gt; 0 else {
            return &quot;0 sec&quot;
        }
        if self &lt; 60 {
            return &quot;\(self) sec&quot;
        }
        if self &lt; 3600 {
            return &quot;\(self / 60) min&quot;
        }
        let hours = self / 3600
        let mins = (self % 3600) / 60

        if hours != 0, mins == 0 {
            return &quot;\(hours)h&quot;
        }
        return &quot;\(hours)h \(mins)m&quot;
    }
}

// MARK: - Methods

public extension SignedInteger {
    /// SwifterSwift: Greatest common divisor of integer value and n.
    ///
    /// - Parameter number: integer value to find gcd with.
    /// - Returns: greatest common divisor of self and n.
    func gcd(of number: Self) -&gt; Self {
        return number == 0 ? self : number.gcd(of: self % number)
    }

    /// SwifterSwift: Least common multiple of integer and n.
    ///
    /// - Parameter number: integer value to find lcm with.
    /// - Returns: least common multiple of self and n.
    func lcm(of number: Self) -&gt; Self {
        return (self * number).abs / gcd(of: number)
    }

    #if canImport(Foundation)
    /// SwifterSwift: Ordinal representation of an integer.
    ///
    ///        print((12).ordinalString()) // prints &quot;12th&quot;
    ///
    /// - Parameter locale: locale, default is .current.
    /// - Returns: string ordinal representation of number in specified locale language. E.g. input 92, output in &quot;en&quot;: &quot;92nd&quot;.
    @available(macOS 10.11, *)
    func ordinalString(locale: Locale = .current) -&gt; String? {
        let formatter = NumberFormatter()
        formatter.locale = locale
        formatter.numberStyle = .ordinal
        guard let number = self as? NSNumber else { return nil }
        return formatter.string(from: number)
    }
    #endif
}
</code></pre>
<h2 id="for-signednumeric"><a class="header" href="#for-signednumeric">for SignedNumeric</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation
#endif

// MARK: - Properties

public extension SignedNumeric {
    /// SwifterSwift: String.
    var string: String {
        return String(describing: self)
    }

    #if canImport(Foundation)
    /// SwifterSwift: String with number and current locale currency.
    var asLocaleCurrency: String? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = Locale.current
        // swiftlint:disable:next force_cast
        return formatter.string(from: self as! NSNumber)
    }
    #endif
}

// MARK: - Methods

public extension SignedNumeric {
    #if canImport(Foundation)
    /// SwifterSwift: Spelled out representation of a number.
    ///
    ///        print((12.32).spelledOutString()) // prints &quot;twelve point three two&quot;
    ///
    /// - Parameter locale: Locale, default is .current.
    /// - Returns: String representation of number spelled in specified locale language. E.g. input 92, output in &quot;en&quot;: &quot;ninety-two&quot;.
    func spelledOutString(locale: Locale = .current) -&gt; String? {
        let formatter = NumberFormatter()
        formatter.locale = locale
        formatter.numberStyle = .spellOut

        guard let number = self as? NSNumber else { return nil }
        return formatter.string(from: number)
    }
    #endif
}
</code></pre>
<h2 id="for-keyeddecodingcontainer"><a class="header" href="#for-keyeddecodingcontainer">for KeyedDecodingContainer</a></h2>
<pre><code class="language-swift">
#if canImport(Foundation)
import Foundation
#endif

public extension KeyedDecodingContainer {
    #if canImport(Foundation)
    /// SwifterSwift: Try to decode a Bool as Int then String before decoding as Bool.
    ///
    /// - Parameter key: Key.
    /// - Returns: Decoded Bool value.
    /// - Throws: Decoding error.
    func decodeBoolAsIntOrString(forKey key: Key) throws -&gt; Bool {
        if let intValue = try? decode(Int.self, forKey: key) {
            return (intValue as NSNumber).boolValue
        } else if let stringValue = try? decode(String.self, forKey: key) {
            return (stringValue as NSString).boolValue
        } else {
            return try decode(Bool.self, forKey: key)
        }
    }
    #endif

    #if canImport(Foundation)
    /// SwifterSwift: Try to decode a Bool as Int then String before decoding as Bool if present.
    ///
    /// - Parameter key: Key.
    /// - Returns: Decoded Bool value.
    /// - Throws: Decoding error.
    func decodeBoolAsIntOrStringIfPresent(forKey key: Key) throws -&gt; Bool? {
        if let intValue = try? decodeIfPresent(Int.self, forKey: key) {
            return (intValue as NSNumber).boolValue
        } else if let stringValue = try? decodeIfPresent(String.self, forKey: key) {
            return (stringValue as NSString).boolValue
        } else {
            return try decodeIfPresent(Bool.self, forKey: key)
        }
    }
    #endif
}
</code></pre>
<h2 id="for-data"><a class="header" href="#for-data">for Data</a></h2>
<pre><code class="language-swift">import Foundation

// MARK: - Data extension

/// This extension add some useful functions to Data.
public extension Data {
    // MARK: - Functions
    
    /// Convert self to a UTF8 String.
    ///
    /// - Returns: Returns self as UTF8 NSString.
    func utf8() -&gt; String? {
        String(data: self, encoding: .utf8)
    }
    
    /// Convert self to a ASCII String.
    ///
    /// - Returns: Returns self as ASCII String.
    func ascii() -&gt; String? {
        String(data: self, encoding: .ascii)
    }
    
    /// Convert self UUID to String.
    ///
    /// Useful for push notifications.
    ///
    /// - Returns: Returns self as String from UUID.
    func readableUUID() -&gt; String {
        description.trimmingCharacters(in: CharacterSet(charactersIn: &quot;&lt;&gt;&quot;)).replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;).replacingOccurrences(of: &quot;-&quot;, with: &quot;&quot;)
    }
}

</code></pre>
<h2 id="for-date"><a class="header" href="#for-date">for Date</a></h2>
<pre><code class="language-swift">
import Foundation

// MARK: - Date extension

/// This extension add some useful functions to Date.
public extension Date {
    // MARK: - Variables
    
    /// Set and get current year.
    var year: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.year, from: self)
        }
        set {
            update(components: [.year: newValue])
        }
    }
    
    /// Set and get current month.
    var month: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.month, from: self)
        }
        set {
            update(components: [.month: newValue])
        }
    }
    
    /// Set and get current day.
    var day: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.day, from: self)
        }
        set {
            update(components: [.day: newValue])
        }
    }
    
    /// Set and get current hour.
    var hour: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.hour, from: self)
        }
        set {
            update(components: [.hour: newValue])
        }
    }
    
    /// Set and get current minute.
    var minute: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.minute, from: self)
        }
        set {
            update(components: [.minute: newValue])
        }
    }
    
    /// Set and get current second.
    var second: Int {
        get {
            #if os(Linux)
                let calendar = Calendar(identifier: .gregorian)
            #else
                let calendar = Calendar.autoupdatingCurrent
            #endif
            
            return calendar.component(.second, from: self)
        }
        set {
            update(components: [.second: newValue])
        }
    }
    
    /// Get current nanosecond.
    var nanosecond: Int {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        return calendar.component(.nanosecond, from: self)
    }
    
    /// Get the weekday number from 
    /// - 1 - Sunday.
    /// - 2 - Monday.
    /// - 3 - Tuerday.
    /// - 4 - Wednesday.
    /// - 5 - Thursday.
    /// - 6 - Friday.
    /// - 7 - Saturday.
    var weekday: Int {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        return calendar.component(.weekday, from: self)
    }
    /// components
    func component(_ unit: Calendar.Component) -&gt; Int {
        let components = systemCalendar.dateComponents([unit], from: self)
        return components.value(for: unit)!
    }
    /// addComponent
    func addComponent(_ value: Int, unit: Calendar.Component) -&gt; Date {
        var dateComponents = DateComponents()
        dateComponents.setValue(value, for: unit)
        return systemCalendar.date(byAdding: dateComponents, to: self)!
    }
    /// toDateComponents
    static func toDateComponents(_ timeInterval: TimeInterval, unit: Calendar.Component) -&gt; DateComponents {
        let date1 = Date()
        let date2 = Date(timeInterval: timeInterval, since: date1)
        return systemCalendar.dateComponents([unit], from: date1, to: date2)
    }
    /// timeInterval
    func timeInterval(_ date: Date, unit: Calendar.Component) -&gt; Int {
        let interval = timeIntervalSince(date)
        let components = Date.toDateComponents(interval, unit: unit)
        return components.value(for: unit)!
    }

    /// Editable date components.
    ///
    /// - year: Year component.
    /// - month: Month component.
    /// - day: Day component.
    /// - hour: Hour component.
    /// - minute: Minute component.
    /// - second: Second component.
    enum EditableDateComponents: Int {
        case year
        case month
        case day
        case hour
        case minute
        case second
    }
    
    // MARK: - Functions
    
    /// Update current Date components.
    ///
    /// - Parameters:
    ///   - components: Dictionary of components and values to be updated.
    mutating func update(components: [EditableDateComponents: Int]) {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        var dateComponents = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second, .nanosecond], from: self)
        
        for (component, value) in components {
            switch component {
            case .year:
                dateComponents.year = value

            case .month:
                dateComponents.month = value

            case .day:
                dateComponents.day = value

            case .hour:
                dateComponents.hour = value

            case .minute:
                dateComponents.minute = value

            case .second:
                dateComponents.second = value
            }
        }
        
        guard let date = calendar.date(from: dateComponents) else {
            return
        }
        
        self = date
    }
    
    /// Creates a Date object from year, month and day as Int.
    ///
    /// - Parameters:
    ///   - year: Year.
    ///   - month: Month.
    ///   - day: Day.
    ///   - hour: Hour.
    ///   - minute: Minute.
    ///   - second: Second.
    init?(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
        var components = DateComponents()
        components.year = year
        components.month = month
        components.day = day
        components.hour = hour
        components.minute = minute
        components.second = second
        
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        guard let date = calendar.date(from: components) else {
            return nil
        }
        self = date
    }
    
    /// Creates a Date object from a date String in a given format.
    ///
    /// - Parameters:
    ///   - dateString: Date String.
    ///   - format: Date String format. Default is &quot;yyyy-MM-dd&quot;. Example: &quot;2014-05-20&quot;.
    ///   - locale: Locale, default is &quot;en_US_POSIX&quot;. You can use Locale.current.identifier.
    init?(parse dateString: String, format: String = &quot;yyyy-MM-dd&quot;, locale: String = &quot;en_US_POSIX&quot;) {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        let dateFormatter = DateFormatter()
        dateFormatter.calendar = calendar
        dateFormatter.locale = Locale(identifier: locale)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = format
        guard let parsed = dateFormatter.date(from: dateString) else {
            return nil
        }
        
        self = parsed
    }
    
    /// Create a Date with other two Date objects.
    /// Taken from the first date: day, month and year.
    /// Taken from the second date: hours and minutes.
    ///
    /// - Parameters:
    ///   - date: The first date for date.
    ///   - time: The second date for time.
    ///   - dateSeparator: Date separator, default is &quot;-&quot;.
    ///   - timeSeparator: Time separator, default is &quot;:&quot;.
    init?(date: Date, time: Date, dateSeparator: String = &quot;-&quot;, timeSeparator: String = &quot;:&quot;) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = &quot;yyyy\(dateSeparator)MM\(dateSeparator)dd&quot;
        let datePortion: String = dateFormatter.string(from: date)
        
        dateFormatter.dateFormat = &quot;HH\(timeSeparator)mm&quot;
        let timePortion: String = dateFormatter.string(from: time)
        
        let dateTime = &quot;\(datePortion) \(timePortion)&quot;
        dateFormatter.dateFormat = &quot;yyyy\(dateSeparator)MM\(dateSeparator)dd HH\(timeSeparator)mm&quot;
        
        guard let parsed = dateFormatter.date(from: dateTime) else {
            return nil
        }
        self = parsed
    }
    
    /// Create an ISO 8601 date from a String.
    ///
    /// - Parameter date: ISO 8601 String.
    init?(iso8601: String) {
        guard let date = Date(parse: iso8601, format: &quot;yyyy-MM-dd'T'HH:mm:ss.SSSZ&quot;) else {
            return nil
        }
        
        self = date
    }
    
    #if !os(Linux)
        /// Creates an ISO 8601 String form 
        ///
        /// - Returns: Returns an ISO 8601 String form 
        func iso8601() -&gt; String {
            let dateFormatter = DateFormatter()
            dateFormatter.calendar = Calendar(identifier: .iso8601)
            dateFormatter.locale = Locale(identifier: &quot;en_US_POSIX&quot;)
            dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
            dateFormatter.dateFormat = &quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX&quot;
            
            return dateFormatter.string(from: self)
        }
    #endif

    /// Get the months number between self and another date.
    ///
    /// - Parameter toDate: The another date.
    /// - Returns: Returns the months between the two dates.
    func monthsBetween(_ toDate: Date) -&gt; Int {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        let components = calendar.dateComponents([.month], from: self, to: toDate)
        
        guard let month = components.month else {
            return 0
        }
        
        return abs(month)
    }
    
    /// Get the days number between self and another date.
    ///
    /// - Parameter anotherDate: The another date.
    /// - Returns: Returns the days between the two dates.
    func daysBetween(_ anotherDate: Date) -&gt; Int {
        let time: TimeInterval = timeIntervalSince(anotherDate)
        return Int(abs(time / 60 / 60 / 24))
    }
    
    /// Returns if self is today.
    ///
    /// - Returns: Returns if self is today.
    func isToday() -&gt; Bool {
        isSame(Date())
    }
    
    /// Compare self with another date.
    ///
    /// - Parameter anotherDate: The another date to compare as Date.
    /// - Returns: Returns true if is same day, otherwise false.
    func isSame(_ anotherDate: Date) -&gt; Bool {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        let componentsSelf = calendar.dateComponents([.year, .month, .day], from: self)
        let componentsAnotherDate = calendar.dateComponents([.year, .month, .day], from: anotherDate)
        
        return componentsSelf.year == componentsAnotherDate.year &amp;&amp; componentsSelf.month == componentsAnotherDate.month &amp;&amp; componentsSelf.day == componentsAnotherDate.day
    }
    
    /// Add days to 
    ///
    /// - Parameter days: The number of days to add.
    /// - Returns: Returns self by adding the gived days number.
    func addingDays(_ days: Int) -&gt; Date? {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        return calendar.date(byAdding: .day, value: days, to: self)
    }
    
    /// Add days to 
    ///
    /// - Parameter days: The number of days to add.
    mutating func addDays(_ days: Int) {
        guard let date = addingDays(days) else {
            return
        }
        
        self = date
    }
    
    /// Get the year string from 
    ///
    /// - Returns: Returns the year string from 
    func yearString() -&gt; String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = &quot;yyyy&quot;
        
        return dateFormatter.string(from: self)
    }
    
    /// Get the String date from 
    ///
    /// - Parameters:
    ///   - format: Date format, default is &quot;yyyy-MM-dd&quot;.
    ///   - locale: Locale, default is &quot;en_US_POSIX&quot;.
    /// - Returns: Returns the String data from 
    func dateString(format: String = &quot;yyyy-MM-dd&quot;, locale: String = &quot;en_US_POSIX&quot;) -&gt; String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: locale)
        dateFormatter.dateFormat = format
        
        return dateFormatter.string(from: self)
    }
    
    /// Returns date with the year, month and day only.
    ///
    /// - Returns: Date after removing all components but not year, month and day.
    func shortDate() -&gt; Date {
        #if os(Linux)
            let calendar = Calendar(identifier: .gregorian)
        #else
            let calendar = Calendar.autoupdatingCurrent
        #endif
        
        let components = calendar.dateComponents([.year, .month, .day], from: self)
        
        guard let date = calendar.date(from: components) else {
            return self
        }
        
        return date
    }
    
    /// Check if the given date is less than 
    ///
    /// - Parameter date: Date to compare.
    /// - Returns: Returns a true if self is greater than another one, otherwise false.
    func isGreaterThan(_ date: Date) -&gt; Bool {
        var isGreater = false
        if compare(date) == ComparisonResult.orderedDescending {
            isGreater = true
        }
        
        return isGreater
    }
    
    /// Check if the given date is greater than 
    ///
    /// - Parameter date: Date to compare.
    /// - Returns: Returns a true if self is less than another one, otherwise false.
    func isLessThan(_ date: Date) -&gt; Bool {
        var isLess = false
        if compare(date) == ComparisonResult.orderedAscending {
            isLess = true
        }
        
        return isLess
    }
    
    /// Just an alias for `isSame(_ anotherDate: Date)`.
    ///
    /// - Parameter date: Date to compare.
    /// - Returns: Returns a true if self is equal to another one, otherwise false.
    func isEqual(_ date: Date) -&gt; Bool {
        isSame(date)
    }
    
    /// Create a Date with the yesterday date.
    ///
    /// - Returns: Returns a Date with the yesterday date.
    func yesterday() -&gt; Date {
        var date = self
        date.day -= 1
        
        return date
    }
    
    /// Get weekday as a localized string from current weekday number.
    ///
    /// - Returns: Return weekday as a localized string.
    func localizedWeekday() -&gt; String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = &quot;EEEE&quot;
        
        if let locale = NSLocale.preferredLanguages.first {
            dateFormatter.locale = Locale(identifier: locale)
        }
        
        return dateFormatter.string(from: self).capitalized
    }
    
    /// Get month as a localized string from current month.
    ///
    /// - Returns: Returns the given month as a localized string.
    func localizedMonth() -&gt; String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = &quot;MMMM&quot;
        
        if let locale = NSLocale.preferredLanguages.first {
            dateFormatter.locale = Locale(identifier: locale)
        }
        
        return dateFormatter.string(from: self).capitalized
    }
    
    /// Get the given Date structure as a formatted string.
    ///
    /// - Parameters:
    ///   - info: The Date to be formatted.
    ///   - dateSeparator: The string to be used as date separator. (Currently does not work on Linux).
    ///   - usFormat: Set if the timestamp is in US format or not.
    ///   - nanosecond: Set if the timestamp has to have the nanosecond.
    /// - Returns: Returns a String in the following format (dateSeparator = &quot;/&quot;, usFormat to false and nanosecond to false). D/M/Y H:M:S. Example: 15/10/2013 10:38:43.
    func description(dateSeparator: String = &quot;/&quot;, usFormat: Bool = false, nanosecond: Bool = false) -&gt; String {
        var description: String
        
        #if os(Linux)
            if usFormat {
                description = String(format: &quot;%04li-%02li-%02li %02li:%02li:%02li&quot;, year, month, day, hour, minute, second)
            } else {
                description = String(format: &quot;%02li-%02li-%04li %02li:%02li:%02li&quot;, month, day, year, hour, minute, second)
            }
        #else
            if usFormat {
                description = String(format: &quot;%04li%@%02li%@%02li %02li:%02li:%02li&quot;, year, dateSeparator, month, dateSeparator, day, hour, minute, second)
            } else {
                description = String(format: &quot;%02li%@%02li%@%04li %02li:%02li:%02li&quot;, month, dateSeparator, day, dateSeparator, year, hour, minute, second)
            }
        #endif
        
        if nanosecond {
            description += String(format: &quot;:%03li&quot;, self.nanosecond / 1_000_000)
        }
        
        return description
    }
}



</code></pre>
<h2 id="for-dictionary-1"><a class="header" href="#for-dictionary-1">for Dictionary</a></h2>
<pre><code class="language-swift">
import Foundation

// MARK: - Dictionary extension

/// This extension adds some useful functions to Dictionary.
public extension Dictionary {
    // MARK: - Functions
    
    /// Append a Value for a given Key in the Dictionary.
    /// If the Key already exist it will be ovrewritten.
    ///
    /// - Parameters:
    ///   - value: Value to be added.
    ///   - key: Key to be added.
    mutating func append(_ value: Value, forKey key: Key) {
        self[key] = value
    }
}

</code></pre>
<h2 id="for-filemanager"><a class="header" href="#for-filemanager">for FileManager</a></h2>
<pre><code class="language-swift">
import Foundation

// MARK: - FileManager extension

/// This extension adds some useful functions to FileManager.
public extension FileManager {
    // MARK: - Variables
    
    /// Path type enum.
    enum PathType: Int {
        /// Main bundle path.
        case mainBundle
        /// Library path.
        case library
        /// Documents path.
        case documents
        /// Cache path.
        case cache
        /// Application Support path.
        case applicationSupport
        /// Temporary path.
        case temporary
    }
    
    // MARK: - Functions
    
    /// Get the path for a PathType.
    ///
    /// - Parameter path: Path type.
    /// - Returns: Returns the path type String.
    func pathFor(_ path: PathType) -&gt; String? {
        var pathString: String?
        
        switch path {
        case .mainBundle:
            pathString = mainBundlePath()

        case .library:
            pathString = libraryPath()

        case .documents:
            pathString = documentsPath()

        case .cache:
            pathString = cachePath()

        case .applicationSupport:
            pathString = applicationSupportPath()

        case .temporary:
            pathString = temporaryPath()
        }
        
        return pathString
    }
    
    /// Save a file with given content.
    ///
    /// - Parameters:
    ///   - file: File to be saved.
    ///   - path: File path.
    ///   - content: Content to be saved.
    /// - Throws: write(toFile:, atomically:, encoding:) errors.
    func save(file: String, in path: PathType, content: String) throws {
        guard let path = FileManager.default.pathFor(path) else {
            return
        }
        
        try content.write(toFile: path.appendingPathComponent(file), atomically: true, encoding: .utf8)
    }
    
    /// Read a file an returns the content as String.
    ///
    /// - Parameters:
    ///   - file: File to be read.
    ///   - path: File path.
    /// - Returns: Returns the content of the file a String.
    /// - Throws: Throws String(contentsOfFile:, encoding:) errors.
    func read(file: String, from path: PathType) throws -&gt; String? {
        guard let path = FileManager.default.pathFor(path) else {
            return nil
        }
        
        return try String(contentsOfFile: path.appendingPathComponent(file), encoding: .utf8)
    }
    
    /// Save an object into a PLIST with given filename.
    ///
    /// - Parameters:
    ///   - object: Object to save into PLIST.
    ///   - path: Path of PLIST.
    ///   - filename: PLIST filename.
    /// - Returns: Returns true if the operation was successful, otherwise false.
    @discardableResult
    func savePlist(object: Any, in path: PathType, filename: String) -&gt; Bool {
        let path = checkPlist(path: path, filename: filename)
        
        guard !path.exist else {
            return NSKeyedArchiver.archiveRootObject(object, toFile: path.path)
        }
        
        return false
    }
    
    /// Load an object from a PLIST with given filename.
    ///
    /// - Parameters:
    ///   - path: Path of PLIST.
    ///   - filename: PLIST filename.
    /// - Returns: Returns the loaded object.
    func readPlist(from path: PathType, filename: String) -&gt; Any? {
        let path = checkPlist(path: path, filename: filename)
        
        guard !path.exist else {
            return NSKeyedUnarchiver.unarchiveObject(withFile: path.path)
        }
        
        return nil
    }
    
    /// Check if plist exist.
    ///
    /// - Parameters:
    ///   - path: Path of plist.
    ///   - filename: Plist filename.
    /// - Returns: Returns if plist exists and path.
    private func checkPlist(path: PathType, filename: String) -&gt; (exist: Bool, path: String) {
        guard let path = FileManager.default.pathFor(path), let finalPath = path.appendingPathComponent(filename).appendingPathExtension(&quot;plist&quot;) else {
            return (false, &quot;&quot;)
        }
        
        return (true, finalPath)
    }
    
    /// Get Main Bundle path for a filename.
    /// If no file is specified, the main bundle path will be returned.
    ///
    /// - Parameter file: Filename.
    /// - Returns: Returns the path as a String.
    func mainBundlePath(file: String = &quot;&quot;) -&gt; String? {
        file.isEmpty ? Bundle.main.bundlePath : Bundle.main.path(forResource: file.deletingPathExtension, ofType: file.pathExtension)
    }
    
    /// Get Documents path for a filename.
    ///
    /// - Parameter file: Filename
    /// - Returns: Returns the path as a String.
    func documentsPath(file: String = &quot;&quot;) -&gt; String? {
        guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        return documentsURL.path.appendingPathComponent(file)
    }
    
    /// Get Library path for a filename.
    ///
    /// - Parameter file: Filename
    /// - Returns: Returns the path as a String.
    func libraryPath(file: String = &quot;&quot;) -&gt; String? {
        guard let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        return libraryURL.path.appendingPathComponent(file)
    }
    
    /// Get Cache path for a filename.
    ///
    /// - Parameter file: Filename
    /// - Returns: Returns the path as a String.
    func cachePath(file: String = &quot;&quot;) -&gt; String? {
        guard let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        return cacheURL.path.appendingPathComponent(file)
    }
    
    /// Get Application Support path for a filename.
    ///
    /// - Parameter file: Filename
    /// - Returns: Returns the path as a String.
    func applicationSupportPath(file: String = &quot;&quot;) -&gt; String? {
        guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        if !FileManager.default.fileExists(atPath: applicationSupportURL.absoluteString, isDirectory: nil) {
            do {
                try FileManager.default.createDirectory(atPath: applicationSupportURL.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                return nil
            }
        }
        
        return applicationSupportURL.path.appendingPathComponent(file)
    }
    
    /// Get Temporary path for a filename.
    ///
    /// - Parameter file: Filename.
    /// - Returns: Returns the path as a String.
    func temporaryPath(file: String = &quot;&quot;) -&gt; String? {
        NSTemporaryDirectory().appendingPathComponent(file)
    }
    
    /// Returns the file size.
    ///
    /// - Parameters:
    ///   - file: Filename.
    ///   - path: Path of the file.
    /// - Returns: Returns the file size.
    /// - Throws: Throws FileManager.default.attributesOfItem(atPath:) errors.
    func size(file: String, from path: PathType) throws -&gt; Float? {
        if !file.isEmpty {
            guard let path = FileManager.default.pathFor(path) else {
                return nil
            }
            
            let finalPath = path.appendingPathComponent(file)
            
            if FileManager.default.fileExists(atPath: finalPath) {
                let fileAttributes = try FileManager.default.attributesOfItem(atPath: finalPath)
                return fileAttributes[FileAttributeKey.size] as? Float
            }
        }
        
        return nil
    }
    
    /// Delete a file with the given filename.
    ///
    /// - Parameters:
    ///   - file: File to delete.
    ///   - path: Path of the file.
    /// - Throws: Throws FileManager.default.removeItem(atPath:) errors.
    func delete(file: String, from path: PathType) throws {
        if !file.isEmpty {
            guard let path = FileManager.default.pathFor(path) else {
                throw BFKitError.pathNotExist
            }
            
            if FileManager.default.fileExists(atPath: path.appendingPathComponent(file)) {
                try FileManager.default.removeItem(atPath: path.appendingPathComponent(file))
            }
        }
    }
    
    /// Move a file from a path to another.
    ///
    /// - Parameters:
    ///   - file: Filename to move.
    ///   - origin: Origin path of the file.
    ///   - destination:  Destination path of the file.
    /// - Returns: Returns true if the operation was successful, otherwise false.
    /// - Throws: Throws FileManager.default.moveItem(atPath:, toPath:) and BFKitError errors.
    func move(file: String, from origin: PathType, to destination: PathType) throws {
        let paths = try check(file: file, origin: origin, destination: destination)
        
        if paths.fileExist {
            try FileManager.default.moveItem(atPath: paths.origin, toPath: paths.destination)
        }
    }
    
    /// Copy a file into another path.
    ///
    /// - Parameters:
    ///   - file: Filename to copy.
    ///   - origin: Origin path
    ///   - destination: Destination path
    /// - Returns: Returns true if the operation was successful, otherwise false.
    /// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:) and BFKitError errors.
    func copy(file: String, from origin: PathType, to destination: PathType) throws {
        let paths = try check(file: file, origin: origin, destination: destination)
        
        if paths.fileExist {
            try FileManager.default.copyItem(atPath: paths.origin, toPath: paths.destination)
        }
    }
    
    /// Check is orign path, destination path and file exists.
    ///
    /// - Parameters:
    ///   - file: File.
    ///   - origin: Origin path.
    ///   - destination: Destination path.
    /// - Returns: Returns a tuple with origin, destination and if file exist.
    /// - Throws: Throws BFKitError errors.
    private func check(file: String, origin: PathType, destination: PathType) throws -&gt; (origin: String, destination: String, fileExist: Bool) { // swiftlint:disable:this large_tuple
        guard let originPath = FileManager.default.pathFor(origin), let destinationPath = FileManager.default.pathFor(destination) else {
            throw BFKitError.pathNotExist
        }
        
        guard destination != .mainBundle else {
            throw BFKitError.pathNotAllowed
        }
        
        let finalOriginPath = originPath.appendingPathComponent(file)
        let finalDestinationPath = destinationPath.appendingPathComponent(file)
        
        guard !FileManager.default.fileExists(atPath: finalOriginPath) else {
            return (finalOriginPath, finalDestinationPath, true)
        }
        
        return (finalOriginPath, finalDestinationPath, false)
    }
    
    /// Rename a file with another filename.
    ///
    /// - Parameters:
    ///   - file: Filename to rename.
    ///   - origin: Origin path.
    ///   - newName: New filename.
    /// - Returns: Returns true if the operation was successful, otherwise false.
    /// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:), FileManager.default.removeItem(atPath:, toPath:) and BFKitError errors.
    func rename(file: String, in origin: PathType, to newName: String) throws {
        guard let originPath = FileManager.default.pathFor(origin) else {
            throw BFKitError.pathNotExist
        }
        
        let finalOriginPath = originPath.appendingPathComponent(file)
        
        if FileManager.default.fileExists(atPath: finalOriginPath) {
            let destinationPath: String = finalOriginPath.replacingOccurrences(of: file, with: newName)
            try FileManager.default.copyItem(atPath: finalOriginPath, toPath: destinationPath)
            try FileManager.default.removeItem(atPath: finalOriginPath)
        }
    }
    
    /// Set settings for object and key. The file will be saved in the Library path if not exist.
    ///
    /// - Parameters:
    ///   - filename: Settings filename. &quot;-Settings&quot; will be automatically added.
    ///   - object: Object to set.
    ///   - objKey: Object key.
    /// - Returns: Returns true if the operation was successful, otherwise false.
    /// - Throws: Throws BFKitError errors.
    @discardableResult
    func setSettings(filename: String, object: Any, forKey objectKey: String) -&gt; Bool {
        guard var path = FileManager.default.pathFor(.applicationSupport) else {
            return false
        }
        
        path = path.appendingPathComponent(&quot;\(filename)-Settings.plist&quot;)
        
        var settings: [String: Any]
        
        if let plistData = try? Data(contentsOf: URL(fileURLWithPath: path)), let plistFile = try? PropertyListSerialization.propertyList(from: plistData, format: nil), let plistDictionary = plistFile as? [String: Any] {
            settings = plistDictionary
        } else {
            settings = [:]
        }
        
        settings[objectKey] = object
        
        do {
            let plistData = try PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0)
            try plistData.write(to: URL(fileURLWithPath: path))
            
            return true
        } catch {
            return false
        }
    }
    
    /// Get settings for key.
    ///
    /// - Parameters:
    ///   - filename: Settings filename. &quot;-Settings&quot; will be automatically added.
    ///   - forKey: Object key.
    /// - Returns: Returns the object for the given key.
    func getSettings(filename: String, forKey objectKey: String) -&gt; Any? {
        guard var path = FileManager.default.pathFor(.applicationSupport) else {
            return nil
        }
        
        path = path.appendingPathComponent(&quot;\(filename)-Settings.plist&quot;)
        
        var settings: [String: Any]
        
        if let plistData = try? Data(contentsOf: URL(fileURLWithPath: path)), let plistFile = try? PropertyListSerialization.propertyList(from: plistData, format: nil), let plistDictionary = plistFile as? [String: Any] {
            settings = plistDictionary
        } else {
            settings = [:]
        }
        
        return settings[objectKey]
    }
}
</code></pre>
<h2 id="for-nsobject"><a class="header" href="#for-nsobject">for NSObject</a></h2>
<pre><code class="language-swift">import Foundation
// MARK: - NSObject exntesion

/// This extension adds some useful functions to NSObject.
public extension NSObject {
    // MARK: - Functions
    
    /// Check if the object is valid (not null).
    ///
    /// - Returns: Returns if the object is valid
    func isValid() -&gt; Bool {
        !(self is NSNull)
    }
}
</code></pre>
<h2 id="for-number"><a class="header" href="#for-number">for Number</a></h2>
<pre><code class="language-swift">import Dispatch
import Foundation

// MARK: - Global functions

/// Degrees to radians conversion.
///
/// - Parameter degrees: Degrees to be converted.
/// - Returns: Returns the convertion result.
public func degreesToRadians(_ degrees: Double) -&gt; Double {
    degrees * Double.pi / 180
}

/// Radians to degrees conversion.
///
/// - Parameter radians: Radians to be converted.
/// - Returns: Returns the convertion result.
public func radiansToDegrees(_ radians: Double) -&gt; Double {
    radians * 180 / Double.pi
}

// MARK: - Extensions

/// This extesion adds some useful functions to Double.
public extension Double {
    /// Gets the individual numbers, and puts them into an array. All negative numbers will start with 0.
    var array: [Int] {
        description.map { Int(String($0)) ?? 0 }
    }
}

/// This extesion adds some useful functions to Float.
public extension Float {
    /// Gets the individual numbers, and puts them into an array. All negative numbers will start with 0.
    var array: [Int] {
        description.map { Int(String($0)) ?? 0 }
    }
}

/// This extesion adds some useful functions to Int.
public extension Int {
    /// Gets the individual numbers, and puts them into an array. All negative numbers will start with 0.
    var array: [Int] {
        description.map { Int(String($0)) ?? 0 }
    }
}

/// Infix operator `&lt;&gt;` with ComparisonPrecedence.
infix operator &lt;&gt;: ComparisonPrecedence

/// Infix operator `&lt;=&gt;` with ComparisonPrecedence.
infix operator &lt;=&gt;: ComparisonPrecedence

/// Returns true if `left` it is in `right` range but not equal.
/// If you want to check if its even equal use the `&lt;=&gt;` operator.
///
/// - Parameters:
///   - left: Left number to be compared.
///   - right: Right tuple to be compared (Number, Number).
/// - Returns: Returns true if `left` it is in `right` range but not equal.
public func &lt;&gt; &lt;T: Comparable&gt;(left: T, right: (T, T)) -&gt; Bool {
    left &gt; right.0 &amp;&amp; left &lt; right.1
}

/// Returns true if `left` is in `right` range or equal.
///
/// - Parameters:
///   - left: Left number to be compared.
///   - right: Right tuple to be compared (Number, Number).
/// - Returns: Returns true if `left` it is in `right` range or equal.
public func &lt;=&gt; &lt;T: Comparable&gt;(left: T, right: (T, T)) -&gt; Bool {
    left &gt;= right.0 &amp;&amp; left &lt;= right.1
}
</code></pre>
<h2 id="for-processinfo"><a class="header" href="#for-processinfo">for ProcessInfo</a></h2>
<pre><code class="language-swift">import Foundation
// MARK: - ProcessInfo extension

/// This extesion adds some useful functions to ProcessInfo.
public extension ProcessInfo {
    /// Returns system uptime.
    ///
    /// - Returns: eturns system uptime.
    static func uptime() -&gt; TimeInterval {
        ProcessInfo.processInfo.systemUptime
    }
    /// Returns sysyem uptime as Date.
    ///
    /// - Returns: Returns sysyem uptime as Date.
    static func uptimeDate() -&gt; Date {
        Date(timeIntervalSinceNow: -uptime())
    }
}
</code></pre>
<h2 id="for-set"><a class="header" href="#for-set">for Set</a></h2>
<pre><code class="language-swift">import Foundation
// MARK: - Set extension

/// This extension adds some useful functions to Set.
public extension Set {
    /// Randomly selects an element from self and returns it.
    ///
    /// - returns: An element that was randomly selected from the set.
    func random() -&gt; Element {
        let randomOffset = Int.random(in: 0...count - 1)
        return self[index(startIndex, offsetBy: randomOffset)]
    }
}
</code></pre>
<h2 id="for-thread"><a class="header" href="#for-thread">for Thread</a></h2>
<pre><code class="language-swift">import Dispatch
import Foundation
// MARK: - Global functions
/// Runs a block on main thread.
///
/// - Parameter block: Block to be executed.
public func runOnMainThread(_ block: @escaping () -&gt; Void) {
    DispatchQueue.main.async {
        block()
    }
}
/// Runs a block in background.
///
/// - Parameter block: block Block to be executed.
public func runInBackground(_ block: @escaping () -&gt; Void) {
    DispatchQueue.global().async {
        block()
    }
}
</code></pre>
<h2 id="for-wkwebview"><a class="header" href="#for-wkwebview">for WKWebView</a></h2>
<pre><code class="language-swift">import Foundation
import WebKit

// MARK: - WKWebView extension

/// This exension adds some useful functions to WKWebView.
public extension WKWebView {
  // MARK: - Functions
  
  /// Load the requested website.
  ///
  /// - Parameter website: Website to load
  func load(website: String) {
    guard let url = URL(string: website) else {
      return
    }
    
    load(URLRequest(url: url))
  }

  func clearCache() {
        let dataStore = WKWebsiteDataStore.default()
        dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
            dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: records) {
                print(&quot;Cache cleared!&quot;)
            }
        }
    }
}

</code></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../posts/swift/learn_swift.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../posts/swift/swiftui_extension.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../posts/swift/learn_swift.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../posts/swift/swiftui_extension.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>



        <script>
            window.playground_line_numbers = true;
        </script>

        <script>
            window.playground_copyable = true;
        </script>

        <script src="../../ace.js"></script>
        <script src="../../editor.js"></script>
        <script src="../../mode-rust.js"></script>
        <script src="../../theme-dawn.js"></script>
        <script src="../../theme-tomorrow_night.js"></script>

        <script src="../../elasticlunr.min.js"></script>
        <script src="../../mark.min.js"></script>
        <script src="../../searcher.js"></script>

        <script src="../../clipboard.min.js"></script>
        <script src="../../highlight.js"></script>
        <script src="../../book.js"></script>

        <!-- Custom JS scripts -->
        <script src="../../src/js/custom.js"></script>


    </div>
    </body>
</html>
